コード例 #1
14
ファイル: args.py プロジェクト: vovchikthebest/PyLaTeX
def test_document():
    geometry_options = {
        "includeheadfoot": True,
        "headheight": "12pt",
        "headsep": "10pt",
        "landscape": True
    }

    doc = Document(
        default_filepath='default_filepath',
        documentclass='article',
        fontenc='T1',
        inputenc='utf8',
        lmodern=True,
        data=None,
        page_numbers=True,
        indent=False,
        document_options=["a4paper", "12pt"],
        geometry_options=geometry_options
    )

    repr(doc)

    doc.append('Some text.')
    doc.change_page_style(style="empty")
    doc.change_document_style(style="plain")
    doc.add_color(name="lightgray", model="gray", description="0.6")
    doc.add_color(name="abitless", model="gray", description="0.8")
    doc.set_variable(name="myVar", value="1234")
    doc.set_variable(name="myVar", value="1234")
    doc.change_length(parameter=r"\headheight", value="0.5in")

    doc.generate_tex(filepath='')
    doc.generate_pdf(filepath='', clean=True)
コード例 #2
0
ファイル: args.py プロジェクト: cmrfrd/PyLaTeX
def test_document():
    geometry_options = {
        "includeheadfoot": True,
        "headheight": "12pt",
        "headsep": "10pt",
        "landscape": True
    }

    doc = Document(default_filepath='default_filepath',
                   documentclass='article',
                   fontenc='T1',
                   inputenc='utf8',
                   lmodern=True,
                   data=None,
                   page_numbers=True,
                   indent=False,
                   document_options=["a4paper", "12pt"],
                   geometry_options=geometry_options)

    repr(doc)

    doc.append('Some text.')
    doc.change_page_style(style="empty")
    doc.change_document_style(style="plain")
    doc.add_color(name="lightgray", model="gray", description="0.6")
    doc.add_color(name="abitless", model="gray", description="0.8")
    doc.set_variable(name="myVar", value="1234")
    doc.set_variable(name="myVar", value="1234")
    doc.change_length(parameter=r"\headheight", value="0.5in")

    doc.generate_tex(filepath='')
    doc.generate_pdf(filepath='', clean=True)
コード例 #3
0
def generate_pdf(stroka):
    pdf_path = get_dir('odli_pdf') + '\\' +stroka.Surname +' '+ stroka.Firstname +' '+ stroka.Patronymic
    logo_image = r'miaclogo.png'

    pdf = Document(pdf_path)
    pdf.packages.add(Package('babel',options='russian'))
    pdf.packages.add(Package('pdfx', options= NoEscape('a-1b') ))
    pdf.packages.add(Package('inputenc',options='utf8'))
    pdf.packages.add(Package('fontenc',options='T2A'))
    pdf.packages.add(Package('geometry',options='a5paper'))

    first_page = PageStyle("firstpage")
    with first_page.create(Head("L")) as header_left:
        with header_left.create(MiniPage(width=NoEscape(r"0.49\textwidth"),pos='l')) as logo_wrapper:
            logo_wrapper.append(StandAloneGraphic(image_options="width=120px",filename=logo_image))
        with header_left.create(MiniPage(width=NoEscape(r"0.49\textwidth"),pos='c')) as logo_wrapper:
            logo_wrapper.append(NoEscape("Сгенерированно в СПб ГБУЗ МИАЦ"))
            logo_wrapper.append(NewLine())
            logo_wrapper.append(NoEscape("В основе данные, предоставленные лабораториями"))
    pdf.preamble.append(first_page)

    pdf.change_document_style("firstpage")
    pdf.add_color(name="lightgray", model="gray", description="0.80")
    pdf.append(HorizontalSpace(size="500px"))
    with pdf.create(Section(NoEscape("Исследование на COVID-19"),numbering=False)):
        pdf.append(NoEscape("Наименование лаборатории: " + stroka.Name_Lab ))
        pdf.append(NewLine())
        pdf.append(NoEscape("Дата исследования: " + stroka.Date_Test))
        pdf.append(NewLine())
        pdf.append(NoEscape("Ответственный за исследование: "))
        pdf.append(NewLine())
        pdf.append(NoEscape(stroka.lab_familia +' '+ stroka.lab_name +' '+ stroka.lab_secondname))
    with pdf.create(Section(NoEscape("Пациент: ") ,numbering=False)):
        pdf.append(LargeText(NoEscape(stroka.Surname +' '+ stroka.Firstname +' '+ stroka.Patronymic)))
        pdf.append(NewLine())
        pdf.append(NewLine())
        pdf.append(NoEscape("Дата рождения: " + stroka.Birthday))
        pdf.append(NewLine())
        pdf.append(NoEscape("Паспорт: " + stroka.Passport))
        pdf.append(NewLine())
        pdf.append(NoEscape("СНИЛС: " + stroka.Snils))
        pdf.append(NewLine())
        pdf.append(NoEscape("ОМС: " + stroka.Policy_OMS))
        pdf.append(NewLine())
        pdf.append(NoEscape("Контактный номер: " + stroka.Phone))
        pdf.append(NewLine())
    with pdf.create(Section(NoEscape("Результат: "),numbering=False)):
        pdf.append(NoEscape("Качественное обнаружение короновируса SARS 2 в различных образцах: "))
        pdf.append(NewLine())
        pdf.append(NewLine())
        if stroka.Result_Test == 'ND':
            pdf.append(TextColor('green',LargeText(NoEscape('Не обнаружено'))))
        if stroka.Result_Test == 'DET':
            pdf.append(TextColor('red',LargeText(NoEscape('Обнаружено'))))

    pdf.generate_pdf(clean_tex=True,compiler='pdflatex')

    with open(pdf_path+'.pdf', "rb") as pdf_file:
        encoded_pdf = base64.b64encode(pdf_file.read()).decode()
    return encoded_pdf
コード例 #4
0
ファイル: PDFCreator.py プロジェクト: sbahrin3/choco-solver
    def publish(self,
                filelist,
                options,
                timPerOpt,
                optPerSol,
                fnames,
                maxtime,
                bestever={},
                plot=True,
                details=True,
                problems="fzn"):
        # Then start the document
        doc = Document(document_options="table")
        doc.packages.append(Package(
            "xcolor", options="dvipsnames"))  # to deal with colors
        doc.color = True  # to deal with colors
        # np.random.seed(0)
        for opt in options:
            col = list(np.random.choice(range(128), size=3))
            doc.add_color(
                opt, "RGB",
                "%d,%d,%d" % (col[0] + 128, col[1] + 128, col[2] + 128))

        doc.preamble.append(
            Command(
                'title',
                'Benchmark analysis of %d problems and %d configurations.' %
                (len(fnames), len(options))))
        doc.preamble.append(Command('author', "Charles Prud'homme"))
        doc.append(NoEscape(r'\maketitle'))

        doc.packages.append(Package('geometry'))

        if plot:
            self.__globals(doc, options, timPerOpt, maxtime)

        self.__sybil(doc, options, optPerSol, fnames, maxtime, bestever)
        if details:
            if problems is "fzn":
                self.__detailsFZN(doc, options, optPerSol, fnames, maxtime,
                                  bestever)
            elif problems is "xcsp":
                self.__detailsXCSP(doc, options, optPerSol, fnames, maxtime,
                                   bestever)

        name = os.path.basename(filelist)
        print(name)
        # doc.generate_tex(name[:-4])
        doc.generate_pdf(filepath=name[:-4], clean=True, silent=False)
コード例 #5
0
ファイル: column_addition.py プロジェクト: ikucan/MathsMonkey
def gen(f_nm, n_ex, n_digits, digit_var, n_nums, n_cols):
    print("----- START -----")

    ttl = 'Column addition - ' + str(n_nums) + ' ' + str(n_digits) + '-digit values with ' + str(digit_var) + '-digit variance'
    
    q_doc = Document(geometry_options = pge_geom, lmodern=True)
    a_doc = Document(geometry_options = pge_geom, lmodern=True)
    
    with q_doc.create(Section("Questions: " + ttl, numbering=False)):
        q_doc.append('Solve the following questions!')

    with a_doc.create(Section("Answers: " + ttl, numbering=False)):
        a_doc.append('Answers to problem sheet')

    q_doc.add_color(name="cream", model="rgb", description=cream_clr_def)
    q_doc.append(Command('fontsize', arguments = ['16', '18']))
    q_doc.append(Command('fontfamily', arguments = ['pcr']))
    q_doc.append(Command('selectfont'))
    q_doc.append(FlushRight())

    a_doc.add_color(name="cream", model="rgb", description=cream_clr_def)
    
    # Add statement table
    with a_doc.create(LongTabu("X[l] " * n_cols,  row_height=2.0)) as a_tbl:
        with q_doc.create(LongTabu("X[r] " * n_cols,  row_height=2.0)) as q_tbl:
            for i in range(round(n_ex/n_cols)):
                row = ['  ' + str(n + i*n_cols) + '.' for n in range(0, n_cols)]
                q_tbl.add_row(row, mapper=bold, color="cream")

                row = [gen_example(n + i*n_cols, n_digits, n_nums, digit_var) for n in range(0, n_cols)]
                q_tbl.add_row([r[0] for r in row])

                if i % 2 == 0:
                    #a_tbl.add_row([r[1] for r in row], color = 'lightgray')
                    a_tbl.add_row([r[1] for r in row], color = 'cream')
                else:
                    a_tbl.add_row([r[1] for r in row])

    # write the file
    q_doc.generate_pdf(out_dir + '/' + f_nm + str(n_digits) + '_digits_Q', clean_tex=False)
    a_doc.generate_pdf(out_dir + '/' + f_nm + str(n_digits) + '_digits_A', clean_tex=False)
    print("----- DONE -----")
コード例 #6
0
def create_latex_file(pokemon, list_of_normal_ivs, list_of_boosted_ivs):
    geometry_options = {
        "landscape": True,
        "margin": "0.5in",
        "headheight": "20pt",
        "headsep": "10pt",
        "includeheadfoot": True
    }

    doc = Document(page_numbers=True, geometry_options=geometry_options)

    doc.add_color('color100', 'rgb', rgb_to_dumb_string(0, 207, 194))
    doc.add_color('color98', 'rgb', rgb_to_dumb_string(60, 141, 1))
    doc.add_color('color96', 'rgb', rgb_to_dumb_string(72, 165, 6))
    doc.add_color('color93', 'rgb', rgb_to_dumb_string(242, 183, 8))
    doc.add_color('color91', 'rgb', rgb_to_dumb_string(246, 96, 0))

    section = Section(f'{pokemon.name} IV Chart')

    table = Tabular('|c|c|c|c|c|c|', row_height=1.5)
    table.add_hline()
    table.add_row((MultiColumn(
        6, align='|c|', data=TextColor('white',
                                       pokemon.name), color='black'), ), )

    table.add_row(
        (MultiColumn(1, align='|c',
                     data='Lv20'), MultiColumn(1, align='c|', data='Lv25'),
         MultiColumn(3, align='c|',
                     data='IV'), MultiColumn(1, align='|c|', data='%')))

    for index in range(len(list_of_normal_ivs)):
        n_iv = list_of_normal_ivs[index]
        b_iv = list_of_boosted_ivs[index]

        row_data = (f'{n_iv.cp}', f'{b_iv.cp}', f'{n_iv.attack}',
                    f'{n_iv.defense}', f'{n_iv.stamina}',
                    f'{n_iv.perfection_percent_rounded}')

        table.add_hline()
        table.add_row(row_data,
                      color=color_by_iv(n_iv.perfection_percent_rounded))

    section.append(table)
    doc.append(section)

    doc.generate_tex(f'latex/{pokemon.name}')
    doc.generate_pdf(f'pdf/{pokemon.name}')
コード例 #7
0
    def start(self, ttl, fnt_sz=[16, 18]):
        q_doc = Document(geometry_options=self.pge_geom, lmodern=True)
        a_doc = Document(geometry_options=self.pge_geom, lmodern=True)

        q_doc.add_color(name="cream",
                        model="rgb",
                        description=self.cream_clr_def)
        q_doc.append(Command('fontsize', arguments=fnt_sz))
        #q_doc.append(Command('fontfamily', arguments = ['pcr']))
        q_doc.append(Command('selectfont'))
        q_doc.append(FlushLeft())

        with q_doc.create(Section("Questions: " + ttl, numbering=False)):
            q_doc.append('Solve questions below:')

        with a_doc.create(Section("Answers: " + ttl, numbering=False)):
            a_doc.append('Answers to problem sheet')

        a_doc.add_color(name="cream",
                        model="rgb",
                        description=self.cream_clr_def)

        self.q_doc = q_doc
        self.a_doc = a_doc
コード例 #8
0
def generate_unique_dw(final_hvs1, final_hvs2, hl1_ch1, hl2_ch1, hl1_ch2,
                       hl2_ch2, sectors):
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "1.0in",
        "includeheadfoot": True
    }
    doc = Document(indent=False, geometry_options=geometry_options)

    # Generating first page style
    first_page = PageStyle("firstpage")

    # Header image
    with first_page.create(Head("L")) as header_left:
        with header_left.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"),
                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(os.path.dirname(__file__),
                                     '../cernlogo.png')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=80px",
                                  filename=logo_file))

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c',
                         align='r')) as title_wrapper:
            title_wrapper.append(LargeText(bold("ATLAS New Small Wheel")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(bold("Integration Tests"))
            title_wrapper.append(LineBreak())
            title_wrapper.append(bold(now.strftime("%d-%m-%Y")))
            title_wrapper.append(LineBreak())
            title_wrapper.append("\n")
            title_wrapper.append(
                LargeText(bold("Double Wedge: " + str(DW_name))))
            title_wrapper.append(LineBreak())

    # Add footer
    with first_page.create(Foot("C")) as footer:

        with footer.create(
                Tabularx(
                    "X X X ",
                    width_argument=NoEscape(r"\textwidth"))) as footer_table:

            footer_table.add_empty_row()

            footer_table.add_hline(color="blue")

            branch_address1 = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                       pos='t')
            branch_address1.append("Lorenzo Pezzotti")
            branch_address1.append("\n")
            branch_address1.append("*****@*****.**")

            branch_address2 = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                       pos='t')
            branch_address2.append("Alan Peyaud")
            branch_address2.append("\n")
            branch_address2.append("*****@*****.**")

            branch_address3 = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                       pos='t')
            branch_address3.append("Ivan Gnesi")
            branch_address3.append("\n")
            branch_address3.append("*****@*****.**")

            document_details = MiniPage(width=NoEscape(r"0.2\textwidth"),
                                        pos='t',
                                        align='r')
            document_details.append(" ")
            document_details.append(LineBreak())
            document_details.append(simple_page_number())

            footer_table.add_row(
                [branch_address1, branch_address2, branch_address3])

    doc.append(first_page)
    # End first page style
    redcircle = glob.glob("redcircle.png")
    redcircle = StandAloneGraphic(redcircle, image_options="width=220px")

    # Add customer information
    with doc.create(Tabu("X[r]")) as first_page_table:
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    doc.append("\n")
    doc.append(timeslot)
    doc.append(LineBreak())

    # IP
    with doc.create(Section('IP SIDE', numbering=False)):
        # first chamber
        # Verify if its SM1, LM1, SM1 or LM2
        if chambername1IP[0:3] == "SM1" or chambername2HO[0:3] == "LM1":
            limit = 10
        else:
            limit = 6

        with doc.create(
                Subsection("Chambers: " + chambername1IP + " + " +
                           chambername2IP,
                           numbering=False)):
            with doc.create(Subsection(chambername1IP, numbering=False)):
                with doc.create(
                        LongTabu("|X[l]|X[r]|X[r]|X[r]|X[r]|X[r]|X[r]|",
                                 row_height=1.5)) as data_table:
                    data_table.add_hline()
                    data_table.add_row(
                        ["Sector", "L1", "L2", "L3", "L4", "HL1", "HL2"],
                        mapper=bold,
                        color="lightgray")
                    data_table.add_hline()
                    row = ["blank", "l1", "l2", "l3", "l4", "hl1", "hl2"]
                    for i, hv in enumerate(final_hvs1[0]):
                        hl1_str = ""
                        hl2_str = ""
                        l1 = ""
                        l2 = ""
                        l3 = ""
                        l4 = ""
                        # assign each sector to a line
                        if hv == hl1_ch1:
                            hl1_str = str(hl1_ch1)
                        elif hv == hl2_ch1:
                            hl2_str = str(hl2_ch1)
                        elif i > limit - 1 + limit * 2:
                            l4 = "570"
                        elif i > limit - 1 + limit:
                            l3 = "570"
                        elif i > limit - 1:
                            l2 = "570"
                        else:
                            l1 = "570"
                        if (i % 2) == 0:
                            data_table.add_row([
                                str(sectors[0][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ])
                        else:
                            data_table.add_row([
                                str(sectors[0][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ],
                                               color="lightgray")
                    data_table.add_hline()

            # second chamber
            if chambername2IP[0:3] == "SM1" or chambername2HO[0:3] == "LM1":
                limit = 10
            else:
                limit = 6
            with doc.create(Subsection(chambername2IP, numbering=False)):
                with doc.create(
                        LongTabu("|X[l]|X[r]|X[r]|X[r]|X[r]|X[r]|X[r]|",
                                 row_height=1.5)) as data_table2:
                    data_table2.add_hline()
                    data_table2.add_row(
                        ["Sector", "L1", "L2", "L3", "L4", "HL1", "HL2"],
                        mapper=bold,
                        color="lightgray")
                    data_table2.add_hline()
                    row = ["blank", "l1", "l2", "l3", "l4", "hl1", "hl2"]
                    for i, hv in enumerate(final_hvs1[1]):
                        hl1_str = ""
                        hl2_str = ""
                        l1 = ""
                        l2 = ""
                        l3 = ""
                        l4 = ""
                        # assign each sector to a line
                        if hv == hl1_ch1:
                            hl1_str = str(hl1_ch1)
                        elif hv == hl2_ch1:
                            hl2_str = str(hl2_ch1)
                        elif i > limit - 1 + limit * 2:
                            l4 = "570"
                        elif i > limit - 1 + limit:
                            l3 = "570"
                        elif i > limit - 1:
                            l2 = "570"
                        else:
                            l1 = "570"

                        if (i % 2) == 0:
                            data_table2.add_row([
                                str(sectors[1][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ])
                        else:
                            data_table2.add_row([
                                str(sectors[1][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ],
                                                color="lightgray")
                    data_table2.add_hline()
    # HO
    # Swap R an L
    final_hvs2[0] = swap(final_hvs2[0])
    final_hvs2[1] = swap(final_hvs2[1])
    if chambername1HO[0:3] == "SM1" or chambername2HO[0:3] == "LM1":
        limit = 10
    else:
        limit = 6
    doc.append(NewPage())
    with doc.create(Section('HO SIDE', numbering=False)):
        # first chamber
        with doc.create(
                Subsection("Chambers: " + chambername1HO + " + " +
                           chambername2HO,
                           numbering=False)):
            with doc.create(Subsection(chambername1HO, numbering=False)):
                with doc.create(
                        LongTabu("|X[l]|X[r]|X[r]|X[r]|X[r]|X[r]|X[r]|",
                                 row_height=1.5)) as data_table3:
                    data_table3.add_hline()
                    data_table3.add_row(
                        ["Sector", "L1", "L2", "L3", "L4", "HL1", "HL2"],
                        mapper=bold,
                        color="lightgray")
                    data_table3.add_hline()
                    row = ["blank", "l1", "l2", "l3", "l4", "hl1", "hl2"]
                    for i, hv in enumerate(final_hvs2[0]):
                        hl1_str = ""
                        hl2_str = ""
                        l1 = ""
                        l2 = ""
                        l3 = ""
                        l4 = ""
                        # assign each sector to a line
                        if hv == hl1_ch2:
                            hl1_str = str(hl1_ch2)
                        elif hv == hl2_ch2:
                            hl2_str = str(hl2_ch2)
                        elif i > limit - 1 + limit * 2:
                            l4 = "570"
                        elif i > limit - 1 + limit:
                            l3 = "570"
                        elif i > limit - 1:
                            l2 = "570"
                        else:
                            l1 = "570"
                        if (i % 2) == 0:
                            data_table3.add_row([
                                str(sectors[2][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ])
                        else:
                            data_table3.add_row([
                                str(sectors[2][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ],
                                                color="lightgray")
                    data_table3.add_hline()

            # second chamber
            if chambername2HO[0:3] == "SM1" or chambername2HO[0:3] == "LM1":
                limit = 10
            else:
                limit = 6
            with doc.create(Subsection(chambername2HO, numbering=False)):
                with doc.create(
                        LongTabu("|X[l]|X[r]|X[r]|X[r]|X[r]|X[r]|X[r]|",
                                 row_height=1.5)) as data_table4:
                    data_table4.add_hline()
                    data_table4.add_row(
                        ["Sector", "L1", "L2", "L3", "L4", "HL1", "HL2"],
                        mapper=bold,
                        color="lightgray")
                    data_table4.add_hline()
                    row = ["blank", "l1", "l2", "l3", "l4", "hl1", "hl2"]
                    for i, hv in enumerate(final_hvs2[1]):
                        hl1_str = ""
                        hl2_str = ""
                        l1 = ""
                        l2 = ""
                        l3 = ""
                        l4 = ""
                        # assign each sector to a line
                        if hv == hl1_ch2:
                            hl1_str = str(hl1_ch2)
                        elif hv == hl2_ch2:
                            hl2_str = str(hl2_ch2)
                        elif i > limit - 1 + limit * 2:
                            l4 = "570"
                        elif i > limit - 1 + limit:
                            l3 = "570"
                        elif i > limit - 1:
                            l2 = "570"
                        else:
                            l1 = "570"

                        if (i % 2) == 0:
                            data_table4.add_row([
                                str(sectors[3][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ])
                        else:
                            data_table4.add_row([
                                str(sectors[3][i]), l1, l2, l3, l4, hl1_str,
                                hl2_str
                            ],
                                                color="lightgray")
                    data_table4.add_hline()
    doc.generate_pdf("complex_report_DW", clean_tex=False, compiler='pdflatex')
コード例 #9
0
ファイル: report.py プロジェクト: dioph/elegant
def latex_report(system, curves, grid, filename):
    lines = system.lines
    trafos = system.trafos
    buses = system.buses
    geometry_options = {"tmargin": "1cm",
                        "lmargin": "1cm",
                        "rmargin": "1cm",
                        "bmargin": "1cm",
                        "includeheadfoot": True}
    doc = Document(page_numbers=True, geometry_options=geometry_options)
    doc.preamble.append(Command('usepackage', 'cmbright'))
    doc.preamble.append(Command('usepackage', 'tikz'))
    doc.preamble.append(Command('usepackage', 'amsmath'))
    doc.preamble.append(Command('usepackage', 'graphicx'))
    now = datetime.datetime.now()
    doc.append(f'Report auto-generated by Elegant at '
               f'{now.day:02d}/{now.month:02d}/{now.year:02d} '
               f'{now.hour:02d}:{now.minute:02d}:{now.second:02d}')
    wye_comm = UnsafeCommand(
        'newcommand', '\\wye',
        extra_arguments=r'\mathbin{\text{\begin{tikzpicture}'
                        r'[x=1pt, y=1pt, scale=2]'
                        r'\draw '
                        r'(-0.9, 0) -- (0.9, 0) '
                        r'(-0.6, -0.5) -- (0.6, -0.5) '
                        r'(-0.3, -1) -- (0.3, -1) '
                        r'(0, 0) -- ++(0, 1.5) -- ++(1.2, 0) coordinate (tmp)'
                        r'-- +(0, -2) '
                        r'(tmp) +(45:2) -- (tmp) -- +(135:2) ;'
                        r'\end{tikzpicture}}}'
    )
    why_comm = UnsafeCommand(
        'newcommand', '\\why',
        extra_arguments=r'\mathbin{\text{\begin{tikzpicture}'
                        r'[x=1pt, y=1pt, scale=2]'
                        r'\draw '
                        r'(1.2, 1.5) coordinate (tmp)'
                        r'-- +(0, -2) '
                        r'(tmp) +(45:2) -- (tmp) -- +(135:2) ;'
                        r'\end{tikzpicture}}}'
    )
    doc.append(wye_comm)
    doc.append(why_comm)
    doc.add_color(name="lightgray", model="gray", description="0.80")
    with doc.create(Section('Buses')):
        with doc.create(Subsection('Load-Flow Solution')):
            with doc.create(LongTable('c|ccccccc')) as tbl:
                tbl.add_hline()
                tbl.add_row(('Bus', NoEscape('$|V|$ (pu)'), NoEscape('$\\delta$ (deg)'),
                             NoEscape('$P_G$ (MW)'), NoEscape('$Q_G$ (Mvar)'),
                             NoEscape('$P_L$ (MW)'), NoEscape('$Q_L$ (Mvar)'),
                             NoEscape('$Z_L$ (pu)')))
                tbl.add_hline()
                tbl.end_table_header()
                tbl.add_hline()
                tbl.add_row((MultiColumn(8, align='r', data='Continued on Next Page'),))
                tbl.add_hline()
                tbl.end_table_footer()
                tbl.add_hline()
                tbl.end_table_last_footer()

                for i, b in enumerate(buses):
                    if i % 2 == 0:
                        color = 'lightgray'
                    else:
                        color = None
                    tbl.add_row((b.bus_id + 1,
                                 NoEscape('{:.04f}'.format(b.v)),
                                 NoEscape('${:.02f}$'.format(b.delta * 180 / np.pi)),
                                 NoEscape('{:.02f}'.format(b.pg * 100)),
                                 NoEscape('{:.02f}'.format(b.qg * 100)),
                                 NoEscape('{:.02f}'.format(b.pl * 100)),
                                 NoEscape('{:.02f}'.format(b.ql * 100)),
                                 safe_repr(b.Z)),
                                color=color)
        with doc.create(Subsection('Fault Calculations')):
            with doc.create(LongTable('c|cccccccccc')) as tbl:
                tbl.add_hline()
                tbl.add_row((MultiRow(2, data='Bus'),
                             MultiColumn(2, align='c', data=NoEscape('TPG')),
                             MultiColumn(2, align='c', data=NoEscape('SLG')),
                             MultiColumn(4, align='c', data=NoEscape('DLG')),
                             MultiColumn(2, align='c', data=NoEscape('LL'))))
                tbl.add_hline(2, 11)
                tbl.add_row(('', NoEscape('$I_A$ (pu)'), NoEscape('$\\delta_A$ (deg)'),
                             NoEscape('$I_A$ (pu)'), NoEscape('$\\delta_A$ (deg)'),
                             NoEscape('$I_B$ (pu)'), NoEscape('$\\delta_B$ (deg)'),
                             NoEscape('$I_C$ (pu)'), NoEscape('$\\delta_C$ (deg)'),
                             NoEscape('$I_B$ (pu)'), NoEscape('$\\delta_B$ (deg)')))
                tbl.add_hline()
                tbl.end_table_header()
                tbl.add_hline()
                tbl.add_row((MultiColumn(11, align='r', data='Continued on Next Page'),))
                tbl.add_hline()
                tbl.end_table_footer()
                tbl.add_hline()
                tbl.end_table_last_footer()

                for i, b in enumerate(buses):
                    if i % 2 == 0:
                        color = 'lightgray'
                    else:
                        color = None
                    tbl.add_row((b.bus_id + 1,
                                 safe_repr(np.abs(b.iTPG)),
                                 NoEscape('${:.02f}$'.format(np.angle(b.iTPG) * 180 / np.pi)),
                                 safe_repr(np.abs(b.iSLG)),
                                 NoEscape('${:.02f}$'.format(np.angle(b.iSLG) * 180 / np.pi)),
                                 safe_repr(np.abs(b.iDLGb)),
                                 NoEscape('${:.02f}$'.format(np.angle(b.iDLGb) * 180 / np.pi)),
                                 safe_repr(np.abs(b.iDLGc)),
                                 NoEscape('${:.02f}$'.format(np.angle(b.iDLGc) * 180 / np.pi)),
                                 safe_repr(np.abs(b.iLL)),
                                 NoEscape('${:.02f}$'.format(np.angle(b.iLL) * 180 / np.pi))),
                                color=color)
    with doc.create(Section('Lines')):
        with doc.create(LongTable('c|cccccccc')) as tbl:
            tbl.add_hline()
            tbl.add_row((MultiRow(2, data='Line'),
                         MultiColumn(3, align='c', data='Parametrization'),
                         MultiColumn(2, align='c', data='Loss'),
                         MultiColumn(3, align='c', data='Flow')))
            tbl.add_hline(2, 9)
            tbl.add_row(('', NoEscape('$R$ (\\%pu)'), NoEscape('$X_L$ (\\%pu)'),
                         NoEscape('$B_C$ (\\%pu)'), NoEscape('$P_{loss}$ (MW)'),
                         NoEscape('$Q_{loss}$ (Mvar)'), NoEscape('$P$ (MW)'),
                         NoEscape('$Q$ (Mvar)'), NoEscape('$I/I_{max}$ (\\%)')))
            tbl.add_hline()
            tbl.end_table_header()
            tbl.add_hline()
            tbl.add_row((MultiColumn(9, align='r', data='Continued on Next Page'),))
            tbl.add_hline()
            tbl.end_table_footer()
            tbl.add_hline()
            tbl.end_table_last_footer()

            for i, lt in enumerate(lines):
                if i % 2 == 0:
                    color = 'lightgray'
                else:
                    color = None
                tbl.add_row((NoEscape('{} -- {}'.format(lt.orig.bus_id + 1, lt.dest.bus_id + 1)),
                             NoEscape('{:.04f}'.format(lt.Zpu.real * 100)),
                             NoEscape('{:.04f}'.format(lt.Zpu.imag * 100)),
                             NoEscape('{:.04f}'.format(lt.Ypu.imag * 100)),
                             NoEscape('{:.02f}'.format(lt.Sper.real * 100)),
                             NoEscape('{:.02f}'.format(lt.Sper.imag * 100)),
                             NoEscape('{:.02f}'.format(lt.S2.real * 100)),
                             NoEscape('{:.02f}'.format(lt.S2.imag * 100)),
                             NoEscape('{:.02f}'.format(np.abs(lt.Ia) / lt.imax * 100))),
                            color=color)
    with doc.create(Section('Trafos')):
        with doc.create(LongTable('c|ccccccc')) as tbl:
            tbl.add_hline()
            tbl.add_row((MultiRow(2, data='Trafo'),
                         MultiColumn(3, align='c', data='Parametrization'),
                         MultiColumn(1, align='c', data='Loss'),
                         MultiColumn(3, align='c', data='Flow')))
            tbl.add_hline(2, 8)
            tbl.add_row(('', NoEscape('$x^+$ (\\%pu)'), NoEscape('$x^0$ (\\%pu)'),
                         'Configuration', NoEscape('$Q_{loss}$ (Mvar)'),
                         NoEscape('$P$ (MW)'), NoEscape('$Q$ (Mvar)'), NoEscape('$S/S_N$ (\\%)')))
            tbl.add_hline()
            tbl.end_table_header()
            tbl.add_hline()
            tbl.add_row((MultiColumn(8, align='r', data='Continued on Next Page'),))
            tbl.add_hline()
            tbl.end_table_footer()
            tbl.add_hline()
            tbl.end_table_last_footer()

            for i, tr in enumerate(trafos):
                if i % 2 == 0:
                    color = 'lightgray'
                else:
                    color = None
                tbl.add_row((NoEscape('{} -- {}'.format(tr.orig.bus_id + 1, tr.dest.bus_id + 1)),
                             NoEscape('{:.02f}'.format(tr.Z1.imag * 100)),
                             NoEscape('{:.02f}'.format(tr.Z0.imag * 100)),
                             get_scheme(tr),
                             NoEscape('{:.02f}'.format(tr.Sper.imag * 100)),
                             NoEscape('{:.02f}'.format(tr.S2.real * 100)),
                             NoEscape('{:.02f}'.format(tr.S2.imag * 100)),
                             NoEscape('{:.02f}'.format(np.abs(tr.S2) * 1e8 / tr.snom * 100))),
                            color=color)

    filepath = filename.strip('.pdf')
    make_system_schematic(curves, grid, initial_fontsize=9)
    doc.append(NewPage())
    with doc.create(Section('System')):
        with doc.create(Figure(position='h')) as system_pic:
            system_pic.add_plot(bbox_inches='tight', width=NoEscape('\\textwidth'))
    doc.generate_pdf(filepath, clean_tex=True, compiler='latexmk', compiler_args=['-pdf'])
コード例 #10
0
    def save_latex(self, reportsummary, filename, rel_path, Disp_3d_image):
        companyname = str(reportsummary["ProfileSummary"]['CompanyName'])
        companylogo = str(reportsummary["ProfileSummary"]['CompanyLogo'])
        groupteamname = str(reportsummary["ProfileSummary"]['Group/TeamName'])
        designer = str(reportsummary["ProfileSummary"]['Designer'])
        projecttitle = str(reportsummary['ProjectTitle'])
        subtitle = str(reportsummary['Subtitle'])
        jobnumber = str(reportsummary['JobNumber'])
        client = str(reportsummary['Client'])

        header = PageStyle("header")
        # Create center header
        with header.create(Head("C")):
            with header.create(Tabularx('|l|p{6cm}|l|X|')) as table:
                table.add_hline()
                # MultiColumn(4)
                table.add_row(('Company Name', companyname, 'Project Title',
                               projecttitle),
                              color='OsdagGreen')
                table.add_hline()
                table.add_row(
                    ('Group/Team Name', groupteamname, 'Subtitle', subtitle),
                    color='OsdagGreen')
                table.add_hline()
                table.add_row(('Designer', designer, 'Job Number', jobnumber),
                              color='OsdagGreen')
                table.add_hline()
                table.add_row(
                    ('Date', time.strftime("%d /%m /%Y"), 'Client', client),
                    color='OsdagGreen')
                table.add_hline()
        # Create right footer
        with header.create(Foot("R")):
            header.append(NoEscape(r'Page \thepage'))

        geometry_options = {
            "top": "1.2in",
            "bottom": "1in",
            "left": "0.6in",
            "right": "0.6in",
            "headsep": "0.8in"
        }
        doc = Document(geometry_options=geometry_options, indent=False)
        doc.packages.append(Package('amsmath'))
        doc.packages.append(Package('graphicx'))
        doc.packages.append(Package('needspace'))
        doc.add_color('OsdagGreen', 'HTML', 'D5DF93')
        doc.preamble.append(header)
        doc.change_document_style("header")

        with doc.create(Section('Design Conclusion')):
            with doc.create(Tabularx('|X|X|', row_height=1.2)) as table:
                table.add_hline()
                table.add_row(('Section Designation', 'Remarks'),
                              color='OsdagGreen')
                table.add_hline()
                table.add_row(
                    (reportsummary['Define Section']['Section Designation'],
                     'Pass'))
                table.add_hline()

        with doc.create(Section('Section Details')):
            with doc.create(Tabularx('|X|X|', row_height=1.2)) as table:
                table.add_hline()
                table.add_row(
                    (bold('Section Type'),
                     reportsummary['Define Section']['Section Type']))
                table.add_hline()
                table.add_row(
                    (bold('Section Template'),
                     reportsummary['Define Section']['Section Template']))
                table.add_hline()

        with doc.create(Section('Section Parameters')):
            with doc.create(Tabularx('|X|X|', row_height=1.2)) as table:
                for parameter in reportsummary['Define Section'][
                        'Section Parameters']:
                    para = reportsummary['Define Section'][
                        'Section Parameters'][parameter]
                    table.add_hline()
                    table.add_row((bold(para[0]), para[1]))
                table.add_hline()

        labels = [
            'Area, a(cm²)',
            'Moment of Inertia',
            'I_zz(cm4)',
            'I_yy(cm4)',
            'Radius of Gyration',
            'r_zz(cm)',
            'r_yy(cm)',
            'Centriod',
            'c_z(cm)',
            'c_y(cm)',
            'Plastic Section modulus',
            'Z_pz(cm³)',
            'Z_py(cm³)',
            'Elastic Section modulus',
            'Z_zz(cm³)',
            'Z_yy(cm³)',
        ]
        values = list(reportsummary['Section Properties'].values())
        Properties = [
            (labels[0], values[0]),
            (labels[1], ""),
            (labels[2], values[1]),
            (labels[3], values[2]),
            (labels[4], ""),
            (labels[5], values[3]),
            (labels[6], values[4]),
            (labels[7], ""),
            (labels[8], values[5]),
            (labels[9], values[6]),
            (labels[10], ""),
            (labels[11], values[7]),
            (labels[12], values[8]),
            (labels[13], ""),
            (labels[14], values[9]),
            (labels[15], values[10]),
        ]

        with doc.create(Section('Section Properties')):
            with doc.create(Tabularx('|X|X|', row_height=1.2)) as table:
                for ppty in Properties:
                    table.add_hline()
                    table.add_row((bold(ppty[0]), ppty[1]))
                table.add_hline()
        doc.append(NewPage())

        if (not 'TRAVIS' in os.environ):
            with doc.create(Section('3D View')):
                with doc.create(Figure(position='h!')) as view_3D:
                    view_3dimg_path = rel_path + Disp_3d_image
                    # view_3D.add_image(filename=view_3dimg_path, width=NoEscape(r'\linewidth'))
                    view_3D.add_image(filename=view_3dimg_path)

                    view_3D.add_caption('3D View')
        try:
            doc.generate_pdf(filename, compiler='pdflatex', clean_tex=False)
        except:
            pass
コード例 #11
0
def generate_unique(cpm):
    geometry_options = {
        "head": "60pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    first_page = PageStyle("firstpage")

    with first_page.create(Head("L")) as header_left:
        with header_left.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c',
                         align='L')) as logo_wrapper:
            logo_file = os.path.join(current_app.root_path,
                                     "static/logo/sf.png")
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=120px",
                                  filename=logo_file))

    with first_page.create(Head("R")) as header_right:
        with header_right.create(
                MiniPage(width=NoEscape(r'0.49\textwidth'), pos='c',
                         align='r')) as wrapper_right:
            wrapper_right.append(LargeText(bold('SOCIALFISH')))
            wrapper_right.append(LineBreak())
            wrapper_right.append(MediumText(bold('UNDEADSEC')))
            wrapper_right.append(LineBreak())
            wrapper_right.append(NoEscape(r'\today'))

    with first_page.create(Head('C')) as header_center:
        header_center.append('CAPTURE REPORT')

    with first_page.create(Foot("C")) as footer:
        message = "Important message please read"

    doc.preamble.append(first_page)

    with doc.create(Tabu("X[l] X[r]")) as first_page_table:
        customer = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')

        branch = MiniPage(width=NoEscape(r"0.49\textwidth"),
                          pos='t!',
                          align='r')

        first_page_table.add_row([customer, branch])
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    with doc.create(LongTabu("X[15l]", row_height=1.8)) as data_table:
        data_table.add_row(["Organization\nCapture IP\nBrowser\nLog\n"],
                           mapper=bold,
                           color="lightgray")
        data_table.add_empty_row()
        data_table.add_hline()

        result_query, result_count = generate_report(cpm)
        x = 0

        for i in range(result_count):

            url = result_query[1 + x].split('//')[1]
            ip = result_query[7 + x]
            log_dict = literal_eval(result_query[2 + x])

            if 'skstamp' in log_dict.keys():
                rm_trash = log_dict.pop('skstamp')
            elif 'utf8' in log_dict.keys():
                rm_trash = log_dict.pop('utf8')

            browser = result_query[4 + x] + ' v' + result_query[5 + x]
            x = 8 * (i + 1)

            row_tex = [
                url + '\n' + ip + '\n' + browser + '\n' + str(log_dict) + '\n'
            ]

            if (i % 2) == 0:
                data_table.add_row(row_tex, color="lightgray")
            else:
                data_table.add_row(row_tex)

    doc.append(NewPage())
    pdf_name = 'Report{}'.format(strftime('-%y%m'))
    doc.generate_pdf(pdf_name, clean_tex=False)
    open_new(os.getcwd() + '/' + pdf_name + '.pdf')
コード例 #12
0
def generate_unique():
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    # Generating first page style
    first_page = PageStyle("firstpage")

    # Header image
    with first_page.create(Head("L")) as header_left:
        with header_left.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"),
                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(os.path.dirname(__file__),
                                     'sample-logo.png')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=120px",
                                  filename=logo_file))

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c',
                         align='r')) as title_wrapper:
            title_wrapper.append(LargeText(bold("Bank Account Statement")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold("Date")))

    # Add footer
    with first_page.create(Foot("C")) as footer:
        message = "Important message please read"
        with footer.create(
                Tabularx(
                    "X X X X",
                    width_argument=NoEscape(r"\textwidth"))) as footer_table:

            footer_table.add_row(
                [MultiColumn(4, align='l', data=TextColor("blue", message))])
            footer_table.add_hline(color="blue")
            footer_table.add_empty_row()

            branch_address = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                      pos='t')
            branch_address.append("960 - 22nd street east")
            branch_address.append("\n")
            branch_address.append("Saskatoon, SK")

            document_details = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                        pos='t',
                                        align='r')
            document_details.append("1000")
            document_details.append(LineBreak())
            document_details.append(simple_page_number())

            footer_table.add_row([
                branch_address, branch_address, branch_address,
                document_details
            ])

    doc.preamble.append(first_page)
    # End first page style

    # Add customer information
    with doc.create(Tabu("X[l] X[r]")) as first_page_table:
        customer = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')
        customer.append("Verna Volcano")
        customer.append("\n")
        customer.append("For some Person")
        customer.append("\n")
        customer.append("Address1")
        customer.append("\n")
        customer.append("Address2")
        customer.append("\n")
        customer.append("Address3")

        # Add branch information
        branch = MiniPage(width=NoEscape(r"0.49\textwidth"),
                          pos='t!',
                          align='r')
        branch.append("Branch no.")
        branch.append(LineBreak())
        branch.append(bold("1181..."))
        branch.append(LineBreak())
        branch.append(bold("TIB Cheque"))

        first_page_table.add_row([customer, branch])
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    # Add statement table
    with doc.create(LongTabu("X[l] X[2l] X[r] X[r] X[r]",
                             row_height=1.5)) as data_table:
        data_table.add_row(
            ["date", "description", "debits($)", "credits($)", "balance($)"],
            mapper=bold,
            color="lightgray")
        data_table.add_empty_row()
        data_table.add_hline()
        row = ["2016-JUN-01", "Test", "$100", "$1000", "-$900"]
        for i in range(30):
            if (i % 2) == 0:
                data_table.add_row(row, color="lightgray")
            else:
                data_table.add_row(row)

    doc.append(NewPage())

    # Add cheque images
    with doc.create(LongTabu("X[c] X[c]")) as cheque_table:
        cheque_file = os.path.join(os.path.dirname(__file__),
                                   'chequeexample.png')
        cheque = StandAloneGraphic(cheque_file, image_options="width=200px")
        for i in range(0, 20):
            cheque_table.add_row([cheque, cheque])

    doc.generate_pdf("complex_report", clean_tex=False)
コード例 #13
0
    def save_latex(self,
                   uiObj,
                   Design_Check,
                   reportsummary,
                   filename,
                   rel_path,
                   Disp_2d_image,
                   Disp_3d_image,
                   module=''):
        companyname = str(reportsummary["ProfileSummary"]['CompanyName'])
        companylogo = str(reportsummary["ProfileSummary"]['CompanyLogo'])
        groupteamname = str(reportsummary["ProfileSummary"]['Group/TeamName'])
        designer = str(reportsummary["ProfileSummary"]['Designer'])
        projecttitle = str(reportsummary['ProjectTitle'])
        subtitle = str(reportsummary['Subtitle'])
        jobnumber = str(reportsummary['JobNumber'])
        client = str(reportsummary['Client'])

        does_design_exist = reportsummary['does_design_exist']
        osdagheader = '/ResourceFiles/images/Osdag_header_report.png'
        # Add document header
        geometry_options = {
            "top": "5cm",
            "hmargin": "2cm",
            "headheight": "100pt",
            "footskip": "100pt",
            "bottom": "5cm"
        }
        doc = Document(geometry_options=geometry_options, indent=False)
        doc.packages.append(Package('amsmath'))
        doc.packages.append(Package('graphicx'))
        doc.packages.append(Package('needspace'))
        doc.append(pyl.Command('fontsize', arguments=[8, 12]))
        doc.append(pyl.Command('selectfont'))

        doc.add_color('OsdagGreen', 'RGB', '153,169,36')
        doc.add_color('PassColor', 'RGB', '153,169,36')
        doc.add_color('Red', 'RGB', '255,0,0')
        doc.add_color('Green', 'RGB', '0,200,0')
        doc.add_color('FailColor', 'HTML', '933A16')
        header = PageStyle("header")
        # Create center header
        with header.create(Head("C")):
            with header.create(Tabularx('|l|p{4cm}|l|X|')) as table:
                table.add_hline()
                # MultiColumn(4)
                table.add_row((
                    MultiColumn(
                        2,
                        align='|c|',
                        data=('' if companylogo is '' else StandAloneGraphic(
                            image_options="height=0.95cm",
                            filename=companylogo))),
                    MultiColumn(2,
                                align='|c|',
                                data=[
                                    'Created with',
                                    StandAloneGraphic(
                                        image_options="width=4.0cm,height=1cm",
                                        filename=rel_path + osdagheader)
                                ]),
                ))
                table.add_hline()
                table.add_row(('Company Name', companyname, 'Project Title',
                               projecttitle),
                              color='OsdagGreen')
                table.add_hline()
                table.add_row(
                    ('Group/Team Name', groupteamname, 'Subtitle', subtitle),
                    color='OsdagGreen')
                table.add_hline()
                table.add_row(('Designer', designer, 'Job Number', jobnumber),
                              color='OsdagGreen')
                table.add_hline()
                table.add_row(
                    ('Date', time.strftime("%d /%m /%Y"), 'Client', client),
                    color='OsdagGreen')
                table.add_hline()

        # Create right footer
        with header.create(Foot("R")):
            header.append(NoEscape(r'Page \thepage'))
        #
        # doc.preamble.append(header)
        # doc.change_document_style("header")

        # Add Heading
        # with doc.create(MiniPage(align='c')):

        doc.preamble.append(header)
        doc.change_document_style("header")
        with doc.create(Section('Input Parameters')):
            with doc.create(
                    LongTable('|p{5cm}|p{2.5cm}|p{1.5cm}|p{3cm}|p{3.5cm}|',
                              row_height=1.2)) as table:
                table.add_hline()
                for i in uiObj:
                    # row_cells = ('9', MultiColumn(3, align='|c|', data='Multicolumn not on left'))
                    if i == "Selected Section Details" or i == KEY_DISP_ANGLE_LIST or i == KEY_DISP_TOPANGLE_LIST or i == KEY_DISP_CLEAT_ANGLE_LIST:
                        # if type(uiObj[i]) == list:
                        continue
                    if type(uiObj[i]) == dict:
                        table.add_hline()
                        sectiondetails = uiObj[i]
                        image_name = sectiondetails[KEY_DISP_SEC_PROFILE]

                        Img_path = '/ResourceFiles/images/' + image_name + '.png'
                        if (len(sectiondetails)) % 2 == 0:
                            # merge_rows = int(round_up(len(sectiondetails),2)/2 + 2)
                            merge_rows = int((len(sectiondetails) / 2)) + 2
                        else:
                            merge_rows = round_up((len(sectiondetails) / 2), 2)
                        if (len(sectiondetails)) % 2 == 0:
                            sectiondetails[''] = ''

                        a = list(sectiondetails.keys())
                        # index=0
                        for x in range(1, (merge_rows + 1)):
                            # table.add_row("Col.Det.",i,columndetails[i])
                            if x == 1:
                                table.add_row((
                                    MultiRow(
                                        merge_rows,
                                        data=StandAloneGraphic(
                                            image_options=
                                            "width=5cm,height=5cm",
                                            filename=rel_path + Img_path)),
                                    MultiColumn(2, align='|c|', data=a[x]),
                                    MultiColumn(2,
                                                align='|c|',
                                                data=sectiondetails[a[x]]),
                                ))
                            elif x <= 4:
                                table.add_row((
                                    '',
                                    MultiColumn(2,
                                                align='|c|',
                                                data=NoEscape(a[x])),
                                    MultiColumn(2,
                                                align='|c|',
                                                data=NoEscape(
                                                    sectiondetails[a[x]])),
                                ))
                            else:
                                table.add_row((
                                    '',
                                    NoEscape(a[x]),
                                    sectiondetails[a[x]],
                                    NoEscape(a[merge_rows + x - 4]),
                                    sectiondetails[a[merge_rows + x - 4]],
                                ))
                            table.add_hline(2, 5)
                    elif uiObj[i] == "TITLE":
                        table.add_hline()
                        table.add_row((MultiColumn(
                            5,
                            align='|c|',
                            data=bold(i),
                        ), ))
                        table.add_hline()
                    elif i == 'Section Size*':
                        table.add_hline()
                        table.add_row((
                            MultiColumn(
                                3,
                                align='|c|',
                                data=i,
                            ),
                            MultiColumn(2,
                                        align='|c|',
                                        data="Ref List of Input Section"),
                        ))
                        table.add_hline()
                    elif len(str(uiObj[i])) > 55 and type(
                            uiObj[i]) != pyl.math.Math:
                        str_len = len(str(uiObj[i]))
                        loop_len = round_up((str_len / 55), 1, 1)
                        for j in range(1, loop_len + 1):
                            b = 55 * j + 1
                            if j == 1:
                                table.add_row((
                                    MultiColumn(3,
                                                align='|c|',
                                                data=MultiRow(loop_len,
                                                              data=i)),
                                    MultiColumn(2,
                                                align='|c|',
                                                data=uiObj[i][0:b]),
                                ))
                            else:
                                table.add_row((
                                    MultiColumn(3,
                                                align='|c|',
                                                data=MultiRow(loop_len,
                                                              data="")),
                                    MultiColumn(2,
                                                align='|c|',
                                                data=uiObj[i][b - 55:b]),
                                ))
                        table.add_hline()
                    else:
                        table.add_hline()
                        table.add_row((
                            MultiColumn(3, align='|c|', data=NoEscape(i)),
                            MultiColumn(2, align='|c|', data=uiObj[i]),
                        ))
                        table.add_hline()
            for i in uiObj:
                if i == 'Section Size*' or i == KEY_DISP_ANGLE_LIST or i == KEY_DISP_TOPANGLE_LIST or i == KEY_DISP_CLEAT_ANGLE_LIST:
                    with doc.create(Subsection("List of Input Section")):
                        # with doc.create(LongTable('|p{8cm}|p{8cm}|', row_height=1.2)) as table:
                        with doc.create(Tabularx('|p{4cm}|X|',
                                                 row_height=1.2)) as table:
                            table.add_hline()
                            table.add_row((
                                MultiColumn(
                                    1,
                                    align='|c|',
                                    data=i,
                                ),
                                MultiColumn(1,
                                            align='|X|',
                                            data=uiObj[i].strip("[]")),
                            ))
                            # str_len = len(uiObj[i])
                            # loop_len = round_up((str_len/100),1,1)
                            # table.add_hline()
                            # for j in range(1,loop_len+1):
                            #     b= 100*j+1
                            #     if j ==1:
                            #         table.add_row((MultiColumn(1, align='|c|', data=i, ),
                            #                        MultiColumn(1, align='|X|', data=uiObj[i][0:b]),))
                            #     else:
                            #         table.add_row((MultiColumn(1, align='|c|', data=" ", ),
                            #                        MultiColumn(1, align='|X|', data=uiObj[i][b-100:b]),))
                            table.add_hline()

        doc.append(
            pyl.Command('Needspace', arguments=NoEscape(r'10\baselineskip')))
        doc.append(NewPage())
        count = 0
        with doc.create(Section('Design Checks')):
            with doc.create(
                    Tabularx(
                        r'|>{\centering}p{12.5cm}|>{\centering\arraybackslash}X|',
                        row_height=1.2)) as table:
                table.add_hline()
                # Fail = TextColor("FailColor", bold("Fail"))
                # Pass = TextColor("PassColor", bold("Pass"))

                if does_design_exist != True:
                    table.add_row(bold('Design Status'),
                                  color_cell("Red", bold("Fail")))
                else:
                    table.add_row(bold('Design Status'),
                                  color_cell("OsdagGreen", bold("Pass")))
                table.add_hline()

            for check in Design_Check:

                if check[0] == 'SubSection':
                    if count >= 1:
                        # doc.append(NewPage())
                        doc.append(
                            pyl.Command(
                                'Needspace',
                                arguments=NoEscape(r'10\baselineskip')))
                    with doc.create(Subsection(check[1])):
                        #########################
                        # if uiObj== "WELDImage":
                        #     table.add_hline()
                        #     table.add_row((MultiColumn(5, align='|c|', data=bold(i), ),))
                        #     table.add_hline()
                        # else:
                        #########################
                        with doc.create(LongTable(check[2], row_height=1.2)
                                        ) as table:  # todo anjali remove
                            table.add_hline()
                            table.add_row(
                                ('Check', 'Required', 'Provided', 'Remarks'),
                                color='OsdagGreen')
                            table.add_hline()
                            table.end_table_header()
                            table.add_hline()
                            count = count + 1
                elif check[0] == "Selected":
                    if count >= 1:
                        # doc.append(NewPage())
                        doc.append(
                            pyl.Command(
                                'Needspace',
                                arguments=NoEscape(r'10\baselineskip')))
                    with doc.create(Subsection(check[1])):
                        with doc.create(LongTable(check[2],
                                                  row_height=1.2)) as table:
                            table.add_hline()
                            for i in uiObj:
                                # row_cells = ('9', MultiColumn(3, align='|c|', data='Multicolumn not on left'))

                                print(i)
                                if type(
                                        uiObj[i]
                                ) == dict and i == 'Selected Section Details':
                                    table.add_hline()
                                    sectiondetails = uiObj[i]
                                    image_name = sectiondetails[
                                        KEY_DISP_SEC_PROFILE]
                                    Img_path = '/ResourceFiles/images/' + image_name + '.png'
                                    if (len(sectiondetails)) % 2 == 0:
                                        # merge_rows = int(round_up(len(sectiondetails),2)/2 + 2)
                                        merge_rows = int(
                                            round_up((len(sectiondetails) /
                                                      2), 1, 0) + 2)
                                    else:
                                        merge_rows = int(
                                            round_up((len(sectiondetails) /
                                                      2), 1, 0) + 1)
                                    print('Hi',
                                          len(sectiondetails) / 2,
                                          round_up(len(sectiondetails), 2) / 2,
                                          merge_rows)
                                    if (len(sectiondetails)) % 2 == 0:
                                        sectiondetails[''] = ''
                                    a = list(sectiondetails.keys())
                                    # index=0
                                    for x in range(1, (merge_rows + 1)):
                                        # table.add_row("Col.Det.",i,columndetails[i])
                                        if x == 1:
                                            table.add_row((
                                                MultiRow(
                                                    merge_rows,
                                                    data=StandAloneGraphic(
                                                        image_options=
                                                        "width=5cm,height=5cm",
                                                        filename=rel_path +
                                                        Img_path)),
                                                MultiColumn(2,
                                                            align='|c|',
                                                            data=NoEscape(
                                                                a[x])),
                                                MultiColumn(
                                                    2,
                                                    align='|c|',
                                                    data=NoEscape(
                                                        sectiondetails[a[x]])),
                                            ))
                                        elif x <= 4:
                                            table.add_row((
                                                '',
                                                MultiColumn(2,
                                                            align='|c|',
                                                            data=NoEscape(
                                                                a[x])),
                                                MultiColumn(
                                                    2,
                                                    align='|c|',
                                                    data=sectiondetails[a[x]]),
                                            ))
                                        else:
                                            table.add_row((
                                                '',
                                                NoEscape(a[x]),
                                                sectiondetails[a[x]],
                                                NoEscape(a[merge_rows + x -
                                                           4]),
                                                sectiondetails[a[merge_rows +
                                                                 x - 4]],
                                            ))

                                        table.add_hline(2, 5)
                            table.add_hline()
                        count = count + 1
                else:

                    if check[3] == 'Fail':
                        table.add_row((NoEscape(check[0])), check[1], check[2],
                                      TextColor("Red", bold(check[3])))
                    else:
                        table.add_row((NoEscape(check[0])), check[1], check[2],
                                      TextColor("OsdagGreen", bold(check[3])))
                    table.add_hline()

        # 2D images
        if len(Disp_2d_image) != 0:

            if module == KEY_DISP_BCENDPLATE or module == KEY_DISP_BB_EP_SPLICE:
                if does_design_exist and sys.platform != 'darwin':
                    doc.append(NewPage())
                    weld_details = rel_path + Disp_2d_image[0]
                    detailing_details = rel_path + Disp_2d_image[1]
                    stiffener_details = rel_path + Disp_2d_image[2]

                    with doc.create(Section('2D Drawings (Typical)')):

                        with doc.create(Figure()) as image:
                            image.add_image(weld_details,
                                            width=NoEscape(r'0.7\textwidth'),
                                            placement=NoEscape(r'\centering'))
                            image.add_caption(
                                'Typical Weld Details -- Beam to End Plate Connection'
                            )
                            # doc.append(NewPage())

                        with doc.create(Figure()) as image_2:
                            image_2.add_image(
                                detailing_details,
                                width=NoEscape(r'0.7\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_2.add_caption('Typical Detailing')
                            # doc.append(NewPage())

                        with doc.create(Figure()) as image_3:
                            image_3.add_image(
                                stiffener_details,
                                width=NoEscape(r'0.9\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_3.add_caption('Typical Stiffener Details')
                            # doc.append(NewPage())

            elif module == KEY_DISP_BASE_PLATE:
                if does_design_exist and sys.platform != 'darwin':
                    doc.append(NewPage())
                    bp_sketch = rel_path + Disp_2d_image[0]
                    bp_detailing = rel_path + Disp_2d_image[1]
                    bp_weld = rel_path + Disp_2d_image[2]
                    bp_anchor = rel_path + Disp_2d_image[3]
                    bp_key = rel_path + Disp_2d_image[4]

                    with doc.create(Section('2D Drawings (Typical)')):
                        with doc.create(Figure()) as image_1:
                            image_1.add_image(
                                bp_sketch,
                                width=NoEscape(r'1.0\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_1.add_caption('Typical Base Plate Details')
                            # doc.append(NewPage())

                        with doc.create(Figure()) as image_2:
                            image_2.add_image(
                                bp_detailing,
                                width=NoEscape(r'1.0\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_2.add_caption('Typical Base Plate Detailing')
                            # doc.append(NewPage())

                        with doc.create(Figure()) as image_3:
                            image_3.add_image(
                                bp_weld,
                                width=NoEscape(r'1.0\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_3.add_caption('Typical Weld Details')
                            # doc.append(NewPage())

                        with doc.create(Figure()) as image_4:
                            image_4.add_image(
                                bp_anchor,
                                width=NoEscape(r'0.5\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_4.add_caption('Typical Anchor Bolt Details')
                            # doc.append(NewPage())

                        if len(Disp_2d_image[-1]) > 0:
                            with doc.create(Figure()) as image_5:
                                image_5.add_image(
                                    bp_key,
                                    width=NoEscape(r'0.9\textwidth'),
                                    placement=NoEscape(r'\centering'))
                                image_5.add_caption(
                                    'Typical Shear Key Details')
                                # doc.append(NewPage())

        if does_design_exist and sys.platform != 'darwin':
            doc.append(NewPage())
            Disp_top_image = "/ResourceFiles/images/top.png"
            Disp_side_image = "/ResourceFiles/images/side.png"
            Disp_front_image = "/ResourceFiles/images/front.png"
            view_3dimg_path = rel_path + Disp_3d_image
            view_topimg_path = rel_path + Disp_top_image
            view_sideimg_path = rel_path + Disp_side_image
            view_frontimg_path = rel_path + Disp_front_image
            with doc.create(Section('3D Views')):
                with doc.create(
                        Tabularx(
                            r'|>{\centering}X|>{\centering\arraybackslash}X|',
                            row_height=1.2)) as table:
                    view_3dimg_path = rel_path + Disp_3d_image
                    view_topimg_path = rel_path + Disp_top_image
                    view_sideimg_path = rel_path + Disp_side_image
                    view_frontimg_path = rel_path + Disp_front_image
                    table.add_hline()
                    table.add_row([
                        StandAloneGraphic(image_options="height=4cm",
                                          filename=view_3dimg_path),
                        StandAloneGraphic(image_options="height=4cm",
                                          filename=view_topimg_path)
                    ])
                    table.add_row('(a) 3D View', '(b) Top View')
                    table.add_hline()
                    table.add_row([
                        StandAloneGraphic(image_options="height=4cm",
                                          filename=view_sideimg_path),
                        StandAloneGraphic(image_options="height=4cm",
                                          filename=view_frontimg_path)
                    ])
                    table.add_row('(c) Side View', '(d) Front View')
                    table.add_hline()
                # with doc.create(Figure(position='h!')) as view_3D:
                #     view_3dimg_path = rel_path + Disp_3d_image
                #     # view_3D.add_image(filename=view_3dimg_path, width=NoEscape(r'\linewidth'))
                #
                #     view_3D.add_image(filename=view_3dimg_path,width=NoEscape(r'\linewidth,height=6.5cm'))
                #
                #     view_3D.add_caption('3D View')

        with doc.create(Section('Design Log')):
            doc.append(
                pyl.Command('Needspace',
                            arguments=NoEscape(r'10\baselineskip')))
            logger_msgs = reportsummary['logger_messages'].split('\n')
            for msg in logger_msgs:
                if ('WARNING' in msg):
                    colour = 'blue'
                elif ('INFO' in msg):
                    colour = 'OsdagGreen'
                elif ('ERROR' in msg):
                    colour = 'red'
                else:
                    continue
                doc.append(TextColor(colour, '\n' + msg))
        try:
            doc.generate_pdf(filename, compiler='pdflatex', clean_tex=False)
        except:
            pass
コード例 #14
0
def generate_unique():
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    # Generating first page style
    first_page = PageStyle("firstpage")

    # Header image
    with first_page.create(Head("L")) as header_left:
        with header_left.create(MiniPage(width=NoEscape(r"0.49\textwidth"),
                                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(os.path.dirname(__file__),
                                     'sample-logo.png')
            logo_wrapper.append(StandAloneGraphic(image_options="width=120px",
                                filename=logo_file))

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(MiniPage(width=NoEscape(r"0.49\textwidth"),
                                 pos='c', align='r')) as title_wrapper:
            title_wrapper.append(LargeText(bold("Bank Account Statement")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold("Date")))

    # Add footer
    with first_page.create(Foot("C")) as footer:
        message = "Important message please read"
        with footer.create(Tabularx(
                           "X X X X",
                           arguments=NoEscape(r"\textwidth"))) as footer_table:

            footer_table.add_row(
                [MultiColumn(4, align='l', data=TextColor("blue", message))])
            footer_table.add_hline(color="blue")
            footer_table.add_empty_row()

            branch_address = MiniPage(
                width=NoEscape(r"0.25\textwidth"),
                pos='t')
            branch_address.append("960 - 22nd street east")
            branch_address.append("\n")
            branch_address.append("Saskatoon, SK")

            document_details = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                        pos='t', align='r')
            document_details.append("1000")
            document_details.append(LineBreak())
            document_details.append(simple_page_number())

            footer_table.add_row([branch_address, branch_address,
                                  branch_address, document_details])

    doc.preamble.append(first_page)
    # End first page style

    # Add customer information
    with doc.create(Tabu("X[l] X[r]")) as first_page_table:
        customer = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')
        customer.append("Verna Volcano")
        customer.append("\n")
        customer.append("For some Person")
        customer.append("\n")
        customer.append("Address1")
        customer.append("\n")
        customer.append("Address2")
        customer.append("\n")
        customer.append("Address3")

        # Add branch information
        branch = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='t!',
                          align='r')
        branch.append("Branch no.")
        branch.append(LineBreak())
        branch.append(bold("1181..."))
        branch.append(LineBreak())
        branch.append(bold("TIB Cheque"))

        first_page_table.add_row([customer, branch])
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    # Add statement table
    with doc.create(LongTabu("X[l] X[2l] X[r] X[r] X[r]",
                             row_height=1.5)) as data_table:
        data_table.add_row(["date",
                            "description",
                            "debits($)",
                            "credits($)",
                            "balance($)"],
                           mapper=bold,
                           color="lightgray")
        data_table.add_empty_row()
        data_table.add_hline()
        row = ["2016-JUN-01", "Test", "$100", "$1000", "-$900"]
        for i in range(30):
            if (i % 2) == 0:
                data_table.add_row(row, color="lightgray")
            else:
                data_table.add_row(row)

    doc.append(NewPage())

    # Add cheque images
    with doc.create(LongTabu("X[c] X[c]")) as cheque_table:
        cheque_file = os.path.join(os.path.dirname(__file__),
                                   'chequeexample.png')
        cheque = StandAloneGraphic(cheque_file, image_options="width=200px")
        for i in range(0, 20):
            cheque_table.add_row([cheque, cheque])

    doc.generate_pdf("complex_report", clean_tex=False)
コード例 #15
0
def generate_unique():
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options,
                   document_options="a4paper")

    # Generating first page style
    first_page = PageStyle("firstpage")

    # Header image
    with first_page.create(Head("L")) as header_left:
        with header_left.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"),
                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(os.path.dirname(__file__), logo_name)
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=50px",
                                  filename=logo_file))

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c',
                         align='r')) as title_wrapper:
            title_wrapper.append(LargeText(bold("Sjain ventures ltd")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold("C-246, Vallabhnagar")))
            title_wrapper.append(LineBreak())
            # title_wrapper.append(TextColor("gray", MediumText(bold("Raipur, CG"))))
            title_wrapper.append(MediumText(bold("Raipur, CG")))

    # Add footer
    # with first_page.create(Foot("C")) as footer:
    #     message = "Important message please read"
    #     with footer.create(Tabularx(
    #             "X X X X",
    #             width_argument=NoEscape(r"\textwidth"))) as footer_table:

    #         footer_table.add_row(
    #             [MultiColumn(4, align='l', data=TextColor("blue", message))])
    #         footer_table.add_hline(color="blue")
    #         footer_table.add_empty_row()

    #         branch_address = MiniPage(
    #             width=NoEscape(r"0.25\textwidth"),
    #             pos='t')
    #         branch_address.append("960 - 22nd street east")
    #         branch_address.append("\n")
    #         branch_address.append("Saskatoon, SK")

    #         document_details = MiniPage(width=NoEscape(r"0.25\textwidth"),
    #                                     pos='t', align='r')
    #         document_details.append("1000")
    #         document_details.append(LineBreak())
    #         document_details.append(simple_page_number())

    #         footer_table.add_row([branch_address, branch_address,
    #                               branch_address, document_details])

    # Newly added
    with first_page.create(Foot("L")) as right_footer:
        with right_footer.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='l',
                         align='l')) as contact_wrapper:
            contact_wrapper.append(MediumText(bold("Alok Kumar Sharma")))
            contact_wrapper.append(LineBreak())
            contact_wrapper.append(MediumText("*****@*****.**"))
            contact_wrapper.append(LineBreak())
            contact_wrapper.append(MediumText("+91 7877681234"))

    doc.preamble.append(first_page)
    # End first page style

    # Add customer information
    with doc.create(Tabu("X[r]")) as first_page_table:
        # customer = MiniPage(width=NoEscape(r"0.9\textwidth"), pos='h')
        # customer.append("Verna Volcano")
        # customer.append("\n")
        # customer.append("For some Person")
        # customer.append("\n")
        # customer.append("Address1")
        # customer.append("\n")
        # customer.append("Address2")
        # customer.append("\n")
        # customer.append("Address3")

        # Add branch information
        branch = MiniPage(width=NoEscape(r"0.49\textwidth"),
                          pos='t!',
                          align='r')
        branch.append("http://sjainventures.com")
        branch.append(LineBreak())
        branch.append("*****@*****.**")
        # branch.append(LineBreak())
        # branch.append("+91 7877681234")

        first_page_table.add_row([branch])  # [customer, branch]
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    # Add statement table
    # with doc.create(LongTabu("X[l] X[2l] X[r] X[r] X[r]",
    #                          row_height=1.5)) as data_table:
    #     data_table.add_row(["date",
    #                         "description",
    #                         "debits($)",
    #                         "credits($)",
    #                         "balance($)"],
    #                        mapper=bold,
    #                        color="lightgray")
    #     data_table.add_empty_row()
    #     data_table.add_hline()
    #     row = ["2016-JUN-01", "Test", "$100", "$1000", "-$900"]
    #     for i in range(25):
    #         if (i % 2) == 0:
    #             data_table.add_row(row, color="lightgray")
    #         else:
    #             data_table.add_row(row)

    with doc.create(Paragraph("Dear Rishikesh,")) as para1:
        para1.append(lorem_ipsum.LOREM_IPSUM_TEXT2)

    # doc.append(NewPage())

    # Add cheque images
    # with doc.create(LongTabu("X[c] X[c]")) as cheque_table:
    #     cheque_file = os.path.join(os.path.dirname(__file__),
    #                                'facebook_logo.png')
    #     cheque = StandAloneGraphic(cheque_file, image_options="width=200px")
    #     for i in range(0, 20):
    #         cheque_table.add_row([cheque, cheque])

    doc.generate_pdf("complex_report", clean_tex=False)
コード例 #16
0
    def generar(self, Carrera, Asignatura, Curso, listaPreguntas, aleatorio):

        today = str(self.__fecha)

        geometry_options = {
            "head": "48pt",
            "margin": "0.5in",
            "bottom": "0.6in",
            "includeheadfoot": True
        }

        doc = Document(geometry_options=geometry_options)

        header = PageStyle("header")  # DEFINIMOS LA VARIABLE CON ESTILO

        #image_filename = os.path.join(os.path.dirname("__file__"), '../static/zigmap.png') # IMAGEN UNAB

        #data_folder = os.path.join("../", "static/zigmap.png")

        #file_to_open = os.path.join(data_folder, "zigmap.png")

        #image_filename = data_folder
        image_filename = "zigmap.png"

        # Generating first page style
        first_page = PageStyle("firstpage")

        # Header image
        with first_page.create(Head("L")) as header_left:

            with header_left.create(
                    SubFigure(
                        position='L',
                        width=NoEscape(r'0.10\linewidth'))) as logo_wrapper:

                print("IMAGEN")
                #logo_wrapper.add_image('zigmap.png', width=NoEscape(r'\linewidth'))

        # Add document title
        with first_page.create(Head("C")) as center_header:
            with center_header.create(
                    MiniPage(width=NoEscape(r"0.49\textwidth"),
                             pos='c',
                             align='c')) as title_wrapper:
                title_wrapper.append(LargeText(bold(self.__nombre)))

        # Add document title
        with first_page.create(Head("R")) as right_header:
            with right_header.create(
                    MiniPage(width=NoEscape(r"0.49\textwidth"),
                             pos='c',
                             align='r')) as title_wrapper:
                #title_wrapper.append(LargeText(bold("Solemne II")))
                #title_wrapper.append(LineBreak())
                title_wrapper.append(MediumText(bold(
                    Asignatura.get_nombreA())))

        # Add footer
        with first_page.create(Foot("C")) as footer:
            message = "Programación II"
            with footer.create(
                    Tabularx("X X X X", width_argument=NoEscape(
                        r"\textwidth"))) as footer_table:

                footer_table.add_row([
                    MultiColumn(4, align='l', data=TextColor("black", message))
                ])
                footer_table.add_hline(color="black")
                footer_table.add_empty_row()

                branch_address = MiniPage(width=NoEscape(r"0.45\textwidth"),
                                          pos='t',
                                          align='l')
                branch_address.append(
                    MediumText("Facultad de " + Carrera.get_facultad()))
                branch_address.append("\n")
                branch_address.append("")

                branch_address2 = MiniPage(width=NoEscape(r"0.10\textwidth"),
                                           pos='t')
                branch_address2.append("")
                branch_address2.append("\n")
                branch_address2.append("")

                document_details = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                            pos='t',
                                            align='r')
                document_details.append(self.__fecha)
                document_details.append(LineBreak())
                document_details.append("")  # simple_page_number()

                footer_table.add_row([
                    branch_address, branch_address2, branch_address2,
                    document_details
                ])

        doc.preamble.append(first_page)
        # End first page style

        ############################################

        ####################################################
        # Add customer information
        with doc.create(Tabu("X[l] X[r]")) as first_page_table:
            customer = MiniPage(width=NoEscape(r"0.55\textwidth"), pos='h')
            customer.append("Nombre: ___________________________________")
            customer.append("\n")
            customer.append("    Rut:  _______________")
            customer.append("\n")
            customer.append("Nota: ______________")
            customer.append("\n")
            customer.append("\n")

            # Add branch information
            branch = MiniPage(width=NoEscape(r"0.35\textwidth"),
                              pos='t!',
                              align='r')

            if self.__unidad == "unidad1":
                branch.append(bold("Unidad: 1"))
            elif self.__unidad == "unidad2":
                branch.append(bold("Unidad: 2"))
            else:
                branch.append(bold("Unidades: 1 & 2"))
            branch.append(LineBreak())

            branch.append(bold("Curso: "))
            branch.append(bold(Curso.get_cod()))
            branch.append(LineBreak())

            branch.append(bold("Ponderación: "))
            branch.append(bold(self.__ponderacion + "%"))
            branch.append(LineBreak())

            first_page_table.add_row([customer, branch])

        doc.append(LargeText(bold("Indicaciones:")))

        # INDICACIONES

        with doc.create(Itemize()) as itemize:
            doc.append(LineBreak())
            itemize.add_item(
                " Lea atentamente los enunciados de cada pregunta antes de contestar."
            )
            itemize.add_item(
                " Conteste su evaluación en silencio, está prohibido conversar o gesticulizar en la sala durante la prueba."
            )
            itemize.add_item(
                " Dispone de 90 minutos para realizar esta evaluación.")
            itemize.add_item(
                " Marque la alternativa con lapiz pasta, no se aceptan marcadas con lapiz grafito."
            )
            itemize.add_item(
                " Utilice solamente sus materiales, está prohibido solicitar materiales a sus compañeros."
            )
            # you can append to existing items
            itemize.append(Command("ldots"))

        doc.change_document_style("firstpage")
        doc.add_color(name="lightgray", model="gray", description="0.80")
        customer.append(LineBreak())

        now = str(datetime.today())

        for p in listaPreguntas:
            with doc.create(Section('Pregunta - ' + p.get_tipo())):

                doc.append(p.get_contenido())

        doc.append(NewPage())

        nombreFile = str(
            self.__nombre) + " - " + self.get_fecha() + " - " + str(aleatorio)

        print(
            "--------------------------ANTES DE DIR------------------------------"
        )

        try:
            # GENERANDO PDF
            doc.generate_pdf(filepath="tests/" + nombreFile,
                             clean_tex=True,
                             clean=True)
            #doc.generate_pdf(dirName + "/" + nombreFile, clean_tex=False)

        except FileNotFoundError as e:
            doc.generate_pdf(filepath="../tests/" + nombreFile,
                             clean_tex=True,
                             clean=True)
コード例 #17
0
def generate_report(main_title, name, title, email, payroll):

    # For saving the report in the Desktop folder
    dir_output=os.path.join(
        '~',
        'Desktop',
        'absconbest_payroll',
        'output'
    )
    dir_output=os.path.expanduser(dir_output)
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    # Generating
    # first page style
    first_page = PageStyle("firstpage")

    # Header image
    with first_page.create(Head("L")) as header_left:
        with header_left.create(
            MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c')
        ) as logo_wrapper:
            logo_file = 'logo.png'
            logo_wrapper.append(
                StandAloneGraphic(
                    image_options="width=120px",
                    filename=logo_file
                )
            )

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(MiniPage(
            width=NoEscape(r"0.49\textwidth"),
            pos='c',
            align='r')
        ) as title_wrapper:
            title_wrapper.append(LargeText(bold('Payroll Report')))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold(main_title)))

    # Add footer
    with first_page.create(Foot("C")):
        first_page.append(simple_page_number())

    doc.preamble.append(first_page)

    #Add employee information
    with doc.create(Tabu("X[l] X[r]")) as first_page_table:
        employee = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')
        employee.append(name)
        employee.append("\n")
        employee.append(title)
        employee.append("\n")
        employee.append(email)

        #Dummy table
        branch = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='t!',
                          align='r')
        # branch.append(bold("1181..."))
        # branch.append(LineBreak())
        # branch.append(bold("TIB Cheque"))

        first_page_table.add_row([employee, branch])
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    #Add payroll table
    with doc.create(LongTabu("X[l] X[c] X[c] X[c] X[r]",
                             row_height=1.5)) as data_table:
        data_table.add_row(['Work',
                            'Rate Per Hour ($)',
                            'Time in Minutes',
                            'Time in Hours',
                            'Wage ($)'],
                           mapper=bold,
                           color="lightgray")
        data_table.add_empty_row()
        data_table.add_hline()

        #Following Pandas' API
        payroll=payroll.reset_index()
        for i in range(len(payroll.index)):
            try:
                row = [payroll['Work'][i],
                       round(payroll['Rate Per Hour'][i],0),
                       round(payroll['TIM'][i],0),
                       round(payroll['TIH'][i],3),
                       round(payroll['Wage'][i],1)]
            except TypeError:
                row = [payroll['Work'][i],
                       'n/a',
                       round(payroll['TIM'][i],0),
                       round(payroll['TIH'][i],3),
                       round(payroll['Wage'][i],1)]
            if (i%2)==0:
                data_table.add_row(row, color="lightgray")
            else:
                data_table.add_row(row)
        # data_table.add_row([payroll['Work'][l_p],
        #                     round(payroll['TIM'][l_p],0),
        #                     round(payroll['TIH'][l_p],3),
        #                     '',
        #                     round(payroll['Wage'][l_p],1)]
        # )

    doc.append(NewPage())

    doc.generate_pdf(
        filepath=os.path.join(
dir_output,
            main_title.lower().replace(" ","_").replace(",",""),
        ),
        clean_tex=True,
        clean=True,
    )
コード例 #18
0
def generate_unique(sectors_notirradiated, hv_notirradiated, spark_notirradiated, irradatgif):
	geometry_options = {
		"head": "40pt",
		"margin": "0.5in",
		"bottom": "1.0in",
		"includeheadfoot": True
	}
	doc = Document(indent=False,geometry_options=geometry_options)

	# Generating first page style
	first_page = PageStyle("firstpage")

	# Header image
	with first_page.create(Head("L")) as header_left:
		with header_left.create(MiniPage(width=NoEscape(r"0.49\textwidth"),
										 pos='c')) as logo_wrapper:
			logo_file = os.path.join(os.path.dirname(__file__),
									 '../cernlogo.png')
			logo_wrapper.append(StandAloneGraphic(image_options="width=80px",
								filename=logo_file))

	# Add document title
	with first_page.create(Head("R")) as right_header:
		with right_header.create(MiniPage(width=NoEscape(r"0.49\textwidth"),
								 pos='c', align='r')) as title_wrapper:
			title_wrapper.append(LargeText(bold("ATLAS New Small Wheel")))
			title_wrapper.append(LineBreak())
			title_wrapper.append(bold("Integration Tests"))
			title_wrapper.append(LineBreak())
			title_wrapper.append(bold(now.strftime("%d-%m-%Y")))
			title_wrapper.append(LineBreak())
			title_wrapper.append("\n")
			title_wrapper.append(LargeText(bold("Chamber: "+str(chambername))))
			title_wrapper.append(LineBreak())
			title_wrapper.append("ID: "+str(ID))
			title_wrapper.append(LineBreak())

	# Add footer
	with first_page.create(Foot("C")) as footer:

		with footer.create(Tabularx(
				"X X X ",
				width_argument=NoEscape(r"\textwidth"))) as footer_table:

			footer_table.add_empty_row()

			footer_table.add_hline(color="blue")

			branch_address1 = MiniPage(
				width=NoEscape(r"0.25\textwidth"),
				pos='t')
			branch_address1.append("Lorenzo Pezzotti")
			branch_address1.append("\n")
			branch_address1.append("*****@*****.**")

			branch_address2 = MiniPage(
				width=NoEscape(r"0.25\textwidth"),
				pos='t')
			branch_address2.append("Alan Peyaud")
			branch_address2.append("\n")
			branch_address2.append("*****@*****.**")

			branch_address3 = MiniPage(
				width=NoEscape(r"0.25\textwidth"),
				pos='t')
			branch_address3.append("Ivan Gnesi")
			branch_address3.append("\n")
			branch_address3.append("*****@*****.**")

			document_details = MiniPage(width=NoEscape(r"0.2\textwidth"),
										pos='t', align='r')
			document_details.append(" ")
			document_details.append(LineBreak())
			document_details.append(simple_page_number())

			footer_table.add_row([branch_address1, branch_address2,
								  branch_address3])

	doc.append(first_page)
	# End first page style
	redcircle = glob.glob("redcircle.png")
	redcircle = StandAloneGraphic(redcircle, image_options="width=220px")

	# Add customer information
	with doc.create(Tabu("X[r]")) as first_page_table:
		'''
		# Add branch information
		branch = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='t!',
						  align='r')
		branch.append("Chamber name: ")
		branch.append(LineBreak())
		branch.append("ID: ")
		branch.append(LineBreak())

		first_page_table.add_row([branch])
		'''
		first_page_table.add_empty_row()

	doc.change_document_style("firstpage")
	doc.add_color(name="lightgray", model="gray", description="0.85")
	doc.add_color(name="lightgray2", model="gray", description="0.6")

	if irradatgif == "y":
		title = "HV irradiated"
	else:
		title = "HV not irradiated"
	with doc.create(Section(title, numbering=False)):
	   # Add statement table
		doc.append("\n")
		doc.append(timeslot)
		doc.append(LineBreak())
		doc.append(str(deltatime/60)+str("_min"))
		doc.append(LineBreak())
		doc.append("Spike_treshold_0.2_uA")
		doc.append(LineBreak())

		with doc.create(LongTabu("|X[l]|X[r]|X[r]|X[r]|X[r]|",
								 row_height=1.5)) as data_table:
			data_table.add_hline()
			data_table.add_row(["Sector",
								"HV",
								"spark/min",
								"Efficiency",
								"Flag"],
							   mapper=bold,
							   color="lightgray2")
			data_table.add_hline()
			data_table.end_table_header()
			data_table.add_hline()
			row = ["sector", "hv","spark", "efficiency", "0 or 1"]
			acceptedlist = []
			not_acc_counter = 0
			pscolor = "blue"
			for i in range(len(hv_notirradiated)):
				if (i % 2) == 0:
					'''
					if int(hv_notirradiated[i]) > 567.9 and spark_notirradiated[i]<1.0:
						accepted = 1
						acceptedlist.append(accepted)

					else:
						accepted = 0
						acceptedlist.append(accepted)
					'''
					if int(hv_notirradiated[i]) > 567.9:
						hvcolor = "black"

					if 548.0 < int(hv_notirradiated[i]) < 567.9:
						hvcolor = "orange"

					if int(hv_notirradiated[i])< 548.0:
						hvcolor = "red"

					if spark_notirradiated[i] > 6.0:
						sparkcolor = "red"

					if spark_notirradiated[i] == 6.0:
						sparkcolor = "orange"

					if spark_notirradiated[i] < 6.0:
						sparkcolor = "black"

					if efficiency[i] < 80.0:
						effcolor = "red"

					if efficiency[i] > 80.0:
						effcolor = "black"

					if efficiency == 80.0:
						effcolor = "orange"

					if sparkcolor == "red" or hvcolor == "red" or effcolor == "red":
						acceptedcolor = "red"
						accepted = 0
						acceptedlist.append(accepted)
						not_acc_counter = not_acc_counter+1

					else:
						acceptedcolor = "black"
						accepted = 1
						acceptedlist.append(accepted)


					data_table.add_row([str(sectors_notirradiated[i]), TextColor(hvcolor,str(int(hv_notirradiated[i]))),
					TextColor(sparkcolor, str(round(spark_notirradiated[i],2))), TextColor(effcolor, str(round(efficiency[i],1))),
					TextColor(acceptedcolor, "V")])
					data_table.add_hline()
				else:
					'''
					if int(hv_notirradiated[i]) > 567.9 and spark_notirradiated[i]<1.0:
						accepted = 1
						acceptedlist.append(accepted)
					else:
						accepted = 0
						acceptedlist.append(accepted)
					'''
					if int(hv_notirradiated[i]) > 567.9:
						hvcolor = "black"

					if 548.0 < int(hv_notirradiated[i]) < 567.9:
						hvcolor = "orange"

					if int(hv_notirradiated[i])< 548.0:
						hvcolor = "red"

					if spark_notirradiated[i] > 6.0:
						sparkcolor = "red"

					if spark_notirradiated[i] == 6.0:
						sparkcolor = "orange"

					if spark_notirradiated[i] < 6.0:
						sparkcolor = "black"

					if efficiency[i] < 80.0:
						effcolor = "red"

					if efficiency[i] > 80.0:
						effcolor = "black"

					if efficiency == 80.0:
						effcolor = "orange"

					if sparkcolor == "red" or hvcolor == "red" or effcolor == "red":
						acceptedcolor = "red"
						accepted = 0
						acceptedlist.append(accepted)
						not_acc_counter = not_acc_counter+1

					else:
						acceptedcolor = "black"
						accepted = 1
						acceptedlist.append(accepted)


					data_table.add_row([str(sectors_notirradiated[i]), TextColor(hvcolor,str(int(hv_notirradiated[i]))),
					TextColor(sparkcolor, str(round(spark_notirradiated[i],2))), TextColor(effcolor, str(round(efficiency[i],1))),
					TextColor(acceptedcolor, "V")], color="lightgray")
					data_table.add_hline()

			data_table.add_hline()
			data_table.add_row("Out of spec", str(len([x for x in hv_notirradiated if x < 548.0])), str(len([x for x in spark_notirradiated if x > 6.0])), str(len([x for x in efficiency if x < 80.0])), str(not_acc_counter))

			data_table.add_empty_row()
			data_table.add_hline()
			data_table.add_row("Chamber efficiency", "","", "", str(round(total_efficiency)))
			data_table.add_hline()
			if "LM2" in chambername:
				newefficiency = efficiency
				newefficiency.pop(4)
				newefficiency.pop(4)
				newefficiency.pop(8)
				newefficiency.pop(8)
				data_table.add_row("Efficiency no LE8", "","", "", str(round(np.mean(newefficiency))))
				data_table.add_hline()

	doc.append(NoEscape('\\clearpage'))
	with doc.create(Section('Summary', numbering=False)):
		piecart.create_pie([acceptedlist.count(1), acceptedlist.count(0)], "piechart.pdf")


		 # Add cheque images
		with doc.create(LongTabu("X[c]")) as summary1_table:
			pie = glob.iglob("piechart.pdf")
			#png_list = [StandAloneGraphic(x, image_options="width=120px") for x in png_list]
			pienew = [StandAloneGraphic(x, image_options="width=220px") for x in pie]
			summary1_table.add_row([pienew[0]])

		#here I have sectors_notirradiated, hv_notirradiated, spark_notirradiated, acceptedlist
		SM1channels = ["L1","R1","L2","R2","L3","R3","L4","R4","L5","R5"]
		SM2channels = ["L6","R6","L7","R7","L8","R8"]

		badresultsall = []
		badresultseta = []
		badresultsstereo = []

		if chambername[0:3] == "SM1":
		   channels = SM1channels
		if chambername[0:3] == "SM2":
		   channels = SM2channels
		if chambername[0:3] == "LM1":
			channels = SM1channels
		if chambername[0:3] == "LM2":
			channels = SM2channels

		for channel in channels:
		   cntall = sum(1 for x, sector in enumerate(sectors_notirradiated) if sector[2:4] == channel and acceptedlist[x] == 1)
		   cnteta = sum(1 for x, sector in enumerate(sectors_notirradiated) if sector[2:4] == channel and (sector[1:2] == "1" or sector[1:2] == "2") and acceptedlist[x] == 1)
		   cntstereo = sum(1 for x, sector in enumerate(sectors_notirradiated) if sector[2:4] == channel and (sector[1:2] == "3" or sector[1:2] == "4") and acceptedlist[x] == 1)
		   badresultsall.append(4-int(cntall))
		   badresultseta.append(2-int(cnteta))
		   badresultsstereo.append(2-int(cntstereo))

		#doc.append(NewPage())

		with doc.create(LongTabu("X[l] X[r] X[r] X[r]",
								 row_height=1.5)) as data_table2:
			data_table2.add_row(["Sector overimposed (from eta side)",
								"Eta",
								"Stereo",
								"Eta+Stereo"],
								mapper=bold,
								color="lightgray2")
			data_table2.add_empty_row()
			data_table2.add_hline()
			row = ["Sector (all layers)", "Out of spec (Eta)", "Out of spec (Stereo)", "Out of spec (E+S)"]

			for i in range(len(channels)):
				if (i % 2) == 0:
					data_table2.add_row([str(channels[i]), str(int(badresultseta[i])), str(badresultsstereo[i]), badresultsall[i]], color="lightgray")
				else:
					data_table2.add_row([str(channels[i]), str(int(badresultseta[i])), str(badresultsstereo[i]), badresultsall[i]])

		with doc.create(LongTabu("X[l] X[r]",
								 row_height=1.5)) as data_table3:
			data_table3.add_row(["Layer",
								"Mean Efficiency"],
								mapper=bold,
								color="lightgray2")
			data_table3.add_empty_row()
			data_table3.add_hline()
			row = ["layers", "efficiency"]
			channelsT3 = ["L1", "L2", "L3", "L4"]
			for i in range(len(layers_efficiency)):
				if (i % 2) == 0:
					data_table3.add_row([str(channelsT3[i]), str(round(layers_efficiency[i],1))], color="lightgray")
				else:
					data_table3.add_row([str(channelsT3[i]), str(round(layers_efficiency[i],1))])

	doc.append(NewPage())

	if irradatgif == "y":
		title = "Current with irradiation"
	else:
		title = "Current with no irradiation"
	with doc.create(Section(title, numbering=False)):

	# Add cheque images
		with doc.create(LongTabu("X[c] X[c] X[c] X[c]")) as cheque_table:
			png_list = glob.glob('BB5-i*.pdf')
			png_list.sort(key=os.path.getmtime)
			png_list = [StandAloneGraphic(x, image_options="width=120px") for x in png_list]
			print len(png_list)
			row_image = []
			i = 0
			for image in png_list:
				row_image.append(image)
				i = i +1
				if i==4:
					cheque_table.add_row([row_image[0], row_image[1], row_image[2], row_image[3]])
					row_image = []
					i=0

	png_list = []
	doc.generate_pdf("complex_report", clean_tex=False, compiler='pdflatex')
コード例 #19
0
def generate_unique():
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    # Generating first page style
    first_page = PageStyle("firstpage")
    # Header image
    with first_page.create(Head("C")) as header_center:
        with header_center.create(
                MiniPage(width=NoEscape(r"0.50\textwidth"),
                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(os.path.dirname(__file__),
                                     'sample-logo.png')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=300px",
                                  filename=logo_file))

    # Add document title
    # Add footer
    with first_page.create(Foot("C")) as footer:
        message = "Important message please read"
        with footer.create(
                Tabularx(
                    "X X X X",
                    width_argument=NoEscape(r"\textwidth"))) as footer_table:
            branch_address = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                      pos='t')

            document_details = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                        pos='t',
                                        align='r')
            document_details.append(LineBreak())
            document_details.append(simple_page_number())

            footer_table.add_row([
                branch_address, branch_address, branch_address,
                document_details
            ])

    doc.preamble.append(first_page)
    # End first page style

    # Add customer information
    with doc.create(Tabu("X[l] X[r]")) as first_page_table:
        customer = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')

        # Add branch information
        branch = MiniPage(width=NoEscape(r"0.49\textwidth"),
                          pos='t!',
                          align='r')

        first_page_table.add_row([customer, branch])
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")
    print("Enter the Region")
    R = input(str)

    with doc.create(MiniPage(align='c')):
        doc.append(LargeText(bold("\n\n\n\n\n\n" + R)))
        doc.append(LineBreak())
    print("Enter the adress of home ")
    A = input(str)
    image_filename = os.path.join(os.path.dirname(__file__), 'home.jpg')
    with doc.create(Section('Example : ' + A)):
        with doc.create(Figure(position='h!')) as home_pic:
            home_pic.add_image(image_filename, width='490px')
    with doc.create(Section('Property information :')):
        with doc.create(Itemize()) as itemize:
            print("enter property type")
            x = input(str)
            itemize.add_item(bold("Property type : " + x))
            print("How many bedrooms ?")
            y = input(int)
            itemize.add_item(bold("Bedroom : " + y))
            print("How many bathrooms?")
            z = input(float)
            itemize.add_item(bold("Bathroom : " + z))
            print('Enter the year of built please:')
            a = input(int)
            itemize.add_item(bold("Year built : " + a))
            print('Enter the finished sqft :')
            b = input(int)
            itemize.add_item(bold("Finished sqft : " + b))
            print("Enter the estimate price")
            p1 = input(float)
            print('enter the estimate rent')
            p2 = input(float)
            doc.append(LineBreak())
            table1 = Tabular('|c|c|')
            table1.add_hline()
            table1.add_row(('Estimate price', 'Estimate rent'))
            table1.add_hline()
            table1.add_row((p1 + '$', p2 + '$'))
            table1.add_hline()

        doc.append(table1)
    with doc.create(Section('Financing')):
        with doc.create(Itemize()) as itemize:
            print('Enter type of loan')
            lo = input(str)
            itemize.add_item(bold("Loan Type: " + lo))
            print("Enter loan amount")
            la = input(float)
            itemize.add_item(bold("Loan Amount: " + la))
            print("enter the interest rate with %")
            IR = input(float)
            itemize.add_item(bold("Interest Rate: " + IR + "%"))
            print("enter LTV")
            LTV = input(float)
            itemize.add_item(bold("Loan to Value (LTV): " + LTV + "%"))
            print("enter loan term")
            LT = input(int)
            itemize.add_item(bold("Loan Term: " + LT + "years"))
            print("enter loan payment monthly")
            LPM = input(int)
            print("enter loan payment yearly")
            LPY = input(int)
            itemize.add_item(
                bold("Loan Payment: " + LPM + "(monthly), " + LPY +
                     "(yearly)"))

    with doc.create(Section('Assumptions')):
        with doc.create(Itemize()) as itemize:
            print("enter vacancy rate")
            vr = input(float)
            itemize.add_item(bold('Vacancy Rate' + vr))
            print("property managment")
            pr = input(float)
            itemize.add_item(bold('Property Managment' + pr))
            print("yearly expense")
            yex = input(float)
            itemize.add_item(bold('Yearly Expense incr' + yex))
            print("yearly rent")
            yr = input(float)
            itemize.add_item(bold('Yearly Rent incr' + yr))
            print("yearly equity")
            ye = input(float)
            itemize.add_item(bold('Yearly Equity incr' + ye))
            print("land value")
            lv = input(float)
            itemize.add_item(bold('Land Value' + lv))

        section = Section('Financial projection and expences analysis')
        test1 = Subsection(bold('Financial Projection'))
        test2 = Subsection(bold('Expences'))

        table2 = Tabular('|c|c|c|c|c|c|c|c|c|c|')
        table2.add_hline()
        table2.add_row(("Type", "Year 1", "Year 2", "Year 3", "Year 4",
                        "Year 5", "Year 10", "Year 15", "Year 20", "Year 30"))
        table2.add_hline()
        table2.add_row(("Total Annuel Income", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(("Total Annuel Expenses", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(
            ("Total Annuel Operating Expenses", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(("Total Annual Cash Flow", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(("Property Value", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(("Cash on Cash ROI", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(("Loan Balance", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(("Cumulative Cash Flow", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()
        table2.add_row(("Equity", 6, 7, 8, 8, 8, 8, 8, 8, 8))
        table2.add_hline()

        table3 = Tabular('|c|c|c|')
        table3.add_hline()
        table3.add_row(("   ", "Monthly", "Annually"))
        table3.add_hline()
        table3.add_row(("Repair Cost", 6, 7))
        table3.add_hline()
        table3.add_row(("Vacancy", 6, 7))
        table3.add_hline()
        table3.add_row(("Insurance", 6, 7))
        table3.add_hline()
        table3.add_row(("Taxes", 6, 7))
        table3.add_hline()
        table3.add_row(("hoe", 6, 7))
        table3.add_hline()
        table3.add_row(("Capital Expenditures", 6, 7))
        table3.add_hline()
        table3.add_row(("Property Managment", 6, 7))
        table3.add_hline()
        table3.add_row(("Other Expences", 6, 7))
        table3.add_hline()
        table3.add_row((LargeText(bold("Total")), 6, 7))
        table3.add_hline()

        test1.append(table2)
        test2.append(table3)
        section.append(test1)
        section.append(test2)
        doc.append(section)
        doc.append(LineBreak)
        print('Cap Rate')
        cap = input()
        print('Cash on Cash Return')
        cac = input()
        print('Retur on investment')
        roi = input()

    doc.append(
        LargeText(
            bold('Cap Rate :' + cap + '\n\n' + "Cash on Cash Return" + cac +
                 "\n\n" + "Return on Investment" + roi)))
    doc.generate_pdf("complex_report", clean_tex=False)