Пример #1
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
Пример #2
0
def append_liquor_list(doc, df, own_page):
    # TODO no interaction with dataframe?
    kinds = df[df.Category.isin(['Spirit', 'Vermouth',
                                 'Liqueur'])][['Kind', 'Type']]
    if own_page:
        print "Appending list as new page"
        doc.append(NewPage())
    listing = SamepageEnvironment()
    block = Center()
    if not own_page:
        block.append(HRuleFill())
        block.append(Command('\\'))
    block.append(VerticalSpace('16pt'))
    block.append(TitleText("Included Ingredients"))
    block.append(Command('\\'))
    listing.append(block)
    listing.append(VerticalSpace('12pt'))

    cols = add_paracols_environment(listing, 2, '8pt', sloppy=False)
    with cols.create(FlushRight()):
        for item in kinds.Kind:
            cols.append(LargeText(item))
            cols.append(Command('\\'))
    cols.append(Command('switchcolumn'))
    with cols.create(FlushLeft()):
        for item in kinds.Type:
            cols.append(LargeText(italic(item)))
            cols.append(Command('\\'))

    doc.append(listing)
Пример #3
0
def generate_first_page(schema: PLDSchema, document: Document) -> Document:
    document.append(LargeText(Command("maketitle")))
    document.append(VerticalSpace("4cm"))
    with document.create(Center()) as center:
        center: Center
        center.append(LargeText(bold(schema.subtitle)))
    return document
Пример #4
0
 def create_pdf(self) -> Document:
     questions = functools.reduce(
         lambda a, b: a + b, map(lambda x: x.get_questions(),
                                 self.questions), [])
     doc = Document()
     doc.preamble.append(Package('titling'))
     for i in range(1, self.count + 1):
         random.shuffle(questions)
         with doc.create(Center()):
             doc.append(HugeText(self.header))
         doc.append(bold('Nombre:'))
         doc.append(LineBreak())
         doc.append(bold('ID:'))
         doc.append(LineBreak())
         with doc.create(FlushRight()):
             doc.append(LargeText(f'Examen tipo {i}'))
         enum = Enumerate()
         for question in questions:
             question.append_to_document(doc, enum)
         doc.append(NewPage())
         doc.append('Guía de respuestas')
         doc.append(enum)
         doc.append(NewPage())
         doc.append(Command('setcounter', ['section', '0']))
     return doc
Пример #5
0
    def create_document(self):
        geometry = {
            "head": "40pt",
            "margin": "1in",
            "bottom": "1in",
        }

        doc = Document(geometry_options=geometry)
        page = PageStyle("pagestyle")
        with page.create(Head("L")) as header_left:
            with header_left.create(
                    MiniPage(width=NoEscape(r"0.5\textwidth"),
                             pos="c")) as logo_wrapper:
                logo_file = os.path.join(get_current_directory(),
                                         "assets/" + LOGO).replace("\\", "/")
                logo_wrapper.append(
                    StandAloneGraphic(image_options="width=120px",
                                      filename=logo_file))

        with page.create(Head("R")) as right_header:
            with right_header.create(
                    MiniPage(width=NoEscape(r"0.5\textwidth"),
                             pos="c",
                             align="r")) as title_wrapper:
                title_wrapper.append(LargeText(bold("Vindskjerming")))

        doc.preamble.append(page)
        doc.change_document_style("pagestyle")
        return doc
Пример #6
0
def generate_eva_report():

    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    reportStyle = PageStyle("reportStyle")

    with reportStyle.create(Head("R")) as left_header:
        with left_header.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c',
                         align='l')) as title_wrapper:
            title_wrapper.append(LargeText(bold("RiMEA-Projekt")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold("Anlyse")))

    doc.preamble.append(reportStyle)

    doc.change_document_style("reportStyle")

    with doc.create(LongTabu("X[c] X[c]", row_height=1.5)) as report_table:
        report_table.add_row(["Test", "evacuation time(s)"], mapper=bold)
        report_table.add_hline()

    for i in range(1, 4):
        report_table.add_row(i, get_evac_time(i)[0])

    doc.append(NewPage())

    doc.generate_pdf("RiMEA-Projekt-Evacution-Analyse", clean_tex=False)
Пример #7
0
    def create_pdf(self, filename, ind):
        print("+"*10)
        print("Generating Pdf %s" % (filename))

        doc = Document()

        doc.preamble.append(Command('title',
                            self.data_analysis['title'][ind]))
        doc.preamble.append(Command('author',
                            self.data_analysis['authors'][ind]))
        doc.preamble.append(Command('date',
                            self.data_analysis['year'][ind]))
        doc.append(NoEscape(r'\maketitle'))
        doc.append(LargeText(bold('Abstract\n\n')))
        doc.append('\n')
        doc.append(self.data_analysis['abstract'][ind])
        doc.append('\n\n\n\n')
        doc.append('Keywords Major Topic: \n')
        doc.append(self.data_analysis['keywords_major'][ind])
        doc.append('\nOther keywords: \n')
        doc.append(self.data_analysis['keywords_minor'][ind])
        try:
            doc.generate_pdf(self.latex_dir + filename)
        except:
            fd = open(self.latex_dir + filename + '.error','w')
            fd.write('Error creating pdf')
            fd.close()
        return
Пример #8
0
def printSalary(request, id):
    teacher = Teacher.objects.get(pk=id)
    all_add = tAddEntry.objects.filter(teacher__id=id)
    all_del = tDelEntry.objects.filter(teacher__id=id)
    salary = Salary.objects.get(teacher=teacher)
    length = len(all_add) + 1
    length2 = len(all_del) + 1
    user = User.objects.get(pk=1)
    add = 0
    sub = 0
    total = 0

    geometry_options = {
        "margin": "1in",
        "textwidth": "2in",
        "textheight": "2in",
        "headheight": "0pt",
        "headsep": "0pt",
        "footskip": "0pt"
    }

    doc = Document(geometry_options=geometry_options)
    doc.preamble.append(Command("usepackage", "times"))
    doc.preamble.append(Command("usepackage", "graphicx"))
    doc.documentclass = Command('documentclass',
                                options=['11pt'],
                                arguments=['article'])

    with doc.create(Tabu(" X[c]  X[2r]  ")) as table:
        table.add_row(
            (LargeText(bold(teacher.lastname + "," + teacher.firstname))), "")
        table.add_empty_row()

    with doc.create(Tabu(" | X[c] |  X[2r] | ")) as table:

        table.add_hline()
        table.add_row(bold("Allowance"), "PHP " + str(user.amount))
        table.add_hline()
        table.add_row(bold("Additional"), "")
        for i in all_add:
            table.add_empty_row()
            table.add_row(i.name, "PHP " + str(i.value))
            table.add_hline()
            add = add + i.value
        table.add_row(bold("Deduction"), "")
        for i in all_del:
            table.add_empty_row()
            table.add_row(i.name, "PHP " + str(i.value))
            table.add_hline()
            sub = sub + i.value

        total = user.amount + add - sub
        table.add_row(bold("TOTAL"), "PHP " + str(total))
        table.add_hline()

    doc.generate_pdf(teacher.lastname + "_salary", clean_tex=False)
    image_data = open(teacher.lastname + "_salary.pdf", "rb")
    return HttpResponse(image_data, content_type='application/pdf')
Пример #9
0
def test_basic():
    # Tests the basic commands and environments
    # Basic commands
    new_page = NewPage()
    repr(new_page)

    new_line = NewLine()
    repr(new_line)

    line_break = LineBreak()
    repr(line_break)

    h_fill = HFill()
    repr(h_fill)

    # Basic environments
    huge = HugeText("Huge")
    huge.append("Huge 2")
    repr(huge)

    large = LargeText("Large")
    large.append("Large 2")
    repr(large)

    medium = MediumText("Medium")
    medium.append("Medium 2")
    repr(medium)

    small = SmallText("Small")
    small.append("Small 2")
    repr(small)

    footnote = FootnoteText("Footnote")
    footnote.append("Footnote 2")
    repr(footnote)

    text_color = TextColor("green", "GreenText")
    text_color.append("More Green Text")
    repr(text_color)
Пример #10
0
def test_basic():
    # Tests the basic commands and environments
    # Basic commands
    new_page = NewPage()
    repr(new_page)

    new_line = NewLine()
    repr(new_line)

    line_break = LineBreak()
    repr(line_break)

    h_fill = HFill()
    repr(h_fill)

    # Basic environments
    huge = HugeText("Huge")
    huge.append("Huge 2")
    repr(huge)

    large = LargeText("Large")
    large.append("Large 2")
    repr(large)

    medium = MediumText("Medium")
    medium.append("Medium 2")
    repr(medium)

    small = SmallText("Small")
    small.append("Small 2")
    repr(small)

    footnote = FootnoteText("Footnote")
    footnote.append("Footnote 2")
    repr(footnote)

    text_color = TextColor("green", "GreenText")
    text_color.append("More Green Text")
    repr(text_color)
Пример #11
0
def generate_style(schema: PLDSchema, locale: LocaleDictionary,
                   document: Document) -> Document:
    document.preamble.append(
        UnsafeCommand("newcommand",
                      Command("rowWidth"),
                      extra_arguments=NoEscape("\\linewidth-(\\tabcolsep*2)")))
    document.preamble.append(
        Command('renewcommand',
                NoEscape('\\familydefault'),
                extra_arguments=NoEscape('\\sfdefault')))
    document.preamble.append(
        Command("graphicspath", NoEscape("{assets/}{../assets/}")))
    header = PageStyle("header")
    with header.create(Head("L")) as left_header:
        left_header: Head
        left_header.create(
            StandAloneGraphic("primary_logo.pdf", NoEscape("width=30pt")))
    with header.create(Head("R")) as right_header:
        right_header: Head
        right_header.append(LargeText(locale.project_log_document))
    with header.create(Foot("R")) as right_footer:
        right_footer: Foot
        right_footer.append(
            NoEscape(
                f"{locale.page} \\thepage\\ {locale.of} \\pageref{{LastPage}}")
        )
    with header.create(Foot("L")) as left_footer:
        left_footer: Foot
        left_footer.append(
            StandAloneGraphic("secondary_logo.pdf", NoEscape("width=100pt")))
    document.preamble.append(
        Command(
            "title",
            NoEscape(
                StandAloneGraphic("primary_logo.pdf", NoEscape(
                    "width=100pt")).dumps() + "~\\\\[1cm]\n" +
                locale.project_log_document)))
    now = datetime.date.today()
    document.preamble.append(
        Command("date", f"{now.day}/{now.month}/{now.year}"))
    document.preamble.append(
        Command("author", NoEscape("\\and ".join(schema.authors))))
    document.preamble.append(header)
    document.change_document_style("header")

    return document
Пример #12
0
def compile_document_week(no):
    "produce a pdf of the weeks workout"

    # input accessory lifts for main lifts
    bench = [('Decline DB Press (4 x 12)'), ('Face pull (4 x 12)'),
             ('Low/High flyes ss/w press (4 x 12)'), ('Press ups (4 x Max)')]
    # squat = [('Leg press (4 x 15)'), ('Leg extension (4 x 12)'),
    #          ('Leg curl (4 x 12)'), ('Roll out (4 x Max)')]
    squat = [('Smith Front/Back (4 x 12)'), ('Calf Raises (4 x 12)'),
             ('Walking Lunges (4 x 12)'), ('Roll out (4 x Max)')]
    dead = [('Pendlay Row (4 x 8-12)'), ('Hip thrust (4 x 8-12)'),
            ('Pull up (4 x Max)'), ('Leg raise (4 x 8-12)')]
    press = [('Landmine press (4 x 8-12)'), ('Lateral/Rear raises (4 x 8-12)'),
             ('DB Curls (4 x 8-12)'), ('Roll outs (4 x Max)')]

    acc = [bench, squat, press, dead]

    # input main lifts and one rep maxes
    # last updated 21/03/2017
    main_lifts = [('Bench', 90), ('Squat', 128), ('Military Press', 63),
                  ('Deadlift', 143)]

    date = t.strftime("%d/%m/%Y")
    doc = Document()
    doc.packages.append(Package('geometry', options=['margin=2cm']))
    doc.packages.append(Package('times'))
    doc.packages.append(Package('float'))
    doc.packages.append(Package('graphicx'))
    header = generate_header()
    doc.preamble.append(header)
    doc.change_document_style("header")

    # Add title
    doc.append(LineBreak())
    doc.append(LargeText(bold("8/6/3 Workout Routine")))
    doc.append(LineBreak())
    doc.append(MediumText(bold("As of: " + date)))
    doc.append(LineBreak())

    # Add workout for a week
    gen_week(doc, main_lifts, no, acc)
    date_1 = t.strftime("%Y%m%d")
    directory = "/home/thomas/Documents/workout_print/workouts"
    filename = (directory + "/workout_routine_week_" + str(no) + "_" + date_1)
    doc.generate_pdf(filename, clean_tex=True)
Пример #13
0
    def write_header(self, doc):
        # def write_header(self):

        # Add document header
        header = PageStyle("header")
        # Create left header
        with header.create(Head("L")):
            header.append(
                "Center for Reflected Text Analytics (CRETA)\nUniversity of Stuttgart"
            )
            # header.append(LineBreak())
            # header.append("R3")
        ## Create center header
        # with header.create(Head("C")):
        #    header.append("Company")
        # Create right header
        with header.create(Head("R")):
            header.append(NoEscape(r'\today'))
        ## Create left footer
        # with header.create(Foot("L")):
        #    header.append("Left Footer")
        ## Create center footer
        with header.create(Foot("C")):
            header.append(simple_page_number())
        ## Create right footer
        # with header.create(Foot("R")):
        #    header.append("Right Footer")

        doc.preamble.append(header)
        doc.change_document_style("header")

        # Add Heading
        with doc.create(MiniPage(align='c')):
            doc.append(LargeText(bold("rCAT v0.1")))
            doc.append(LineBreak())
            doc.append(MediumText(bold("Relational Character Analysis Tool")))

        return doc
Пример #14
0
def generate_header():
    geometry_options = {"margin": "0.7in"}
    doc = Document(geometry_options=geometry_options)
    # Add document header
    header = PageStyle("header")
    # Create left header
    with header.create(Head("L")):
        header.append("__")
        header.append(LineBreak())
        header.append("_")
    # Create center header
    with header.create(Head("C")):
        header.append("____")
    # Create right header
    with header.create(Head("R")):
        header.append(simple_page_number())
    # Create left footer
    with header.create(Foot("L")):
        header.append("Left Footer")
    # Create center footer
    with header.create(Foot("C")):
        header.append("Center Footer")
    # Create right footer
    with header.create(Foot("R")):
        header.append("Right Footer")

    doc.preamble.append(header)
    doc.change_document_style("header")

    # Add Heading
    with doc.create(MiniPage(align='l')):
        doc.append(LargeText(bold("INVESTMENT PROPERTY - BUY & HOLD")))
        doc.append(LineBreak())
        doc.append(MediumText(bold(" ")))
    doc.generate_pdf("header", clean_tex=False)

    return print('nice')
Пример #15
0
def generate_header():
    geometry_options = {"margin": "0.7in"}
    doc = Document(geometry_options=geometry_options)
    # Add document header
    header = PageStyle("header")
    # Create left header
    with header.create(Head("L")):
        header.append("Page date: ")
        header.append(LineBreak())
        header.append("R3")
    # Create center header
    with header.create(Head("C")):
        header.append("Company")
    # Create right header
    with header.create(Head("R")):
        header.append(simple_page_number())
    # Create left footer
    with header.create(Foot("L")):
        header.append("Left Footer")
    # Create center footer
    with header.create(Foot("C")):
        header.append("Center Footer")
    # Create right footer
    with header.create(Foot("R")):
        header.append("Right Footer")

    doc.preamble.append(header)
    doc.change_document_style("header")

    # Add Heading
    with doc.create(MiniPage(align='c')):
        doc.append(LargeText(bold("Title")))
        doc.append(LineBreak())
        doc.append(MediumText(bold("As at:")))

    doc.generate_pdf("header", clean_tex=False)
Пример #16
0
 def add_title(self, title):
     with self.doc.create(Center()):
         self.doc.append(LargeText(bold(title)))
Пример #17
0
doc.preamble.append(NoEscape(r'\linespread{1.6}'))

#Generating Title
doc.preamble.append(Command('title', 'Trounceflow Countries: Nigeria'))
doc.preamble.append(Command('author', 'Michael Trounce'))
doc.preamble.append(Command('date', NoEscape(r'\today')))
doc.append(NoEscape(r'\maketitle'))

doc.append(NoEscape(r'\begin{abstract}'))
doc.append(
    "The `Trounceflow Countries' series of `living' documents provide real-time dynamic summaries of macroeconomic data relevant to the flows-and-positions analysis of emerging market debt. These macroeconomic data concentrate on the structure of the government bond market but also include other useful but hard-to-wrangle data such as the structure of the local institutional investor base. The data is obtained from the Trounceflow App (trounceflow.com) and the document data is automatically updated in line with the automatic updates on the App; links to the underlying national sources are also given in the `living' documents."
)
doc.append(
    LargeText(
        "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nThe values presented in this report are the face values of the bonds"
    ))
doc.append(NoEscape(r'\end{abstract}'))
doc.append(NewPage())

#Table of Contents
doc.append(NoEscape(r'\tableofcontents'))
doc.append(NewPage())

#Summary Chapter 1
doc.append(NoEscape(r'\chapter{Executive Summary}'))
doc.append(NewPage())
#1.1
with doc.create(Section('Central Government Debt')):
    with doc.create(Tabular('l|l|r|r')) as table:
        table.add_row(('Date', 'Type', 'USD bn (Total)', 'NGN bn (Total)'))
Пример #18
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)
Пример #19
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')
Пример #20
0
def format_recipe(recipe, display_opts):
    """ Return the recipe in a paragraph in a samepage
    """
    recipe_page = SamepageEnvironment()
    name_line = LargeText(recipe.name)

    if display_opts.origin and 'schubar original' in recipe.origin.lower():
        name_line.append(superscript('*'))
        #name_line.append(superscript(NoEscape('\dag')))

    if display_opts.prices and recipe.max_cost:
        price = util.calculate_price(recipe.max_cost, display_opts.markup)
        name_line.append(DotFill())
        name_line.append(superscript('$'))
        name_line.append(price)
    name_line.append('\n')
    recipe_page.append(name_line)

    if display_opts.prep_line:
        recipe_page.append(
            FootnoteText(recipe.prep_line(extended=True, caps=False) + '\n'))

    if display_opts.info and recipe.info:
        recipe_page.append(SmallText(italic(recipe.info + '\n')))
    for item in recipe.ingredients:
        recipe_page.append(item.str() + '\n')

    if display_opts.variants:
        for variant in recipe.variants:
            recipe_page.append(HorizontalSpace('8pt'))
            recipe_page.append(SmallText(italic(variant + '\n')))

    if display_opts.examples and recipe.examples:  # and recipe.name != 'The Cocktail':
        for e in recipe.examples:
            recipe_page.append(
                FootnoteText(
                    "${cost:.2f} | {abv:.2f}% | {std_drinks:.2f} | {kinds}\n".
                    format(**e._asdict())))

    recipe_page.append(Command('par'))
    return recipe_page
Пример #21
0
with doc.create(MiniPage(align='l')):

    #doc.append(NoEscape(r"\noindent\rule{\textwidth}{1pt}"))
    #doc.append(NewLine())
    doc.append('Name : ' + str(sub_info.Name[0]))
    doc.append('\nAge: ' + str(sub_info.Age[0]))
    doc.append('\nGender: ' + str(sub_info.Gender[0]))
    doc.append('\nUH Id: ' + str(sub_info.UHID[0]))
    doc.append('\nDate: ' + d2)
    doc.append(LineBreak())
    doc.append(NoEscape(r"\noindent\rule{\textwidth}{1pt}"))
    doc.append(NewLine())
    doc.append(LineBreak())

    with doc.create(MiniPage(align='c')):
        doc.append(LargeText(bold('Vowel Triangle Analysis Report')))

# Analysis result and image

with doc.create(Section('Vowel Triangle Analysis')):
    with doc.create(Figure(position='h!')) as img_plot:
        img_plot.add_image(img1, width='300px')
        img_plot.add_caption('Vowel Triangle PLot')
    with doc.create(Subsection('Vowel Triangle')):
        doc.append('Area : ' + str(area))
    doc.append(NoEscape(r"\pagebreak[4]"))

# saving the pdf and tex

doc.generate_pdf(filepath='media/VT.report1', clean_tex=False)
Пример #22
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)
Пример #23
0
    def create(self):
        try:
            self.status['text'] = 'Загрузка, подождите'
            self.root.update()
            # Настройки отступов, языка
            geometry_options = {
                "tmargin": "2cm",
                "lmargin": "3cm",
                "rmargin": "1.5cm",
                "bmargin": "2cm"
            }
            doc = Document(geometry_options=geometry_options)
            doc.packages.add(
                Package('grffile',
                        options=['encoding', 'filenameencoding=utf8']))
            doc.packages.add(Package('babel', options=['russian']))

            # Вставляем логотип МИРЭА
            image_filename = os.path.join(os.path.dirname(__file__),
                                          'логотип.png')
            with doc.create(Figure(position='h!')) as logo:
                logo.add_image(image_filename, width='80px')

            # Обложка
            doc.change_length(r"\TPHorizModule", "1mm")
            doc.change_length(r"\TPVertModule", "1mm")
            with doc.create(MiniPage(width=r"\textwidth")) as page:
                # Центральная часть обложки
                with page.create(TextBlock(180, 0, 0)):
                    page.append(Command('centering'))
                    page.append('МИНОБРНАУКИ РОССИИ\n')
                    page.append(
                        'Федеральное государственное бюджетное образовательное учреждение высшего образования\n'
                    )
                    page.append(
                        MediumText(
                            bold(
                                '«МИРЭА - Российский Технологический Университет»\n'
                            )))
                    page.append(LargeText(bold('РТУ МИРЭА\n')))
                    page.append(LineBreak())
                    page.append(
                        MediumText(
                            bold(
                                'Институт комплексной безопасности и специального приборостроения\n'
                            )))
                    page.append(LineBreak())
                    page.append(
                        'Кафедра КБ-8 «Информационное Противоборство»\n')
                    page.append(LineBreak())
                    page.append(LineBreak())
                    page.append(LineBreak())
                    page.append(LargeText('Отчёт\n'))
                    page.append(f'{str(self.entry1.get())}\n')

                # Правая часть обложки
                with page.create(TextBlock(80, 88, 120)):
                    if self.your_var.get() == 0:
                        page.append('Выполнил:\n')
                        page.append(
                            f'Студент {str(self.entry2.get())} курса\n')
                    else:
                        page.append('Выполнила:\n')
                        page.append(
                            f'Студентка {str(self.entry2.get())} курса\n')
                    page.append(f'Группа {str(self.entry3.get())}\n')
                    page.append(f'Шифр {str(self.entry4.get())}\n')
                    page.append(f'{str(self.entry5.get())}\n')
                    page.append(LineBreak())
                    page.append(LineBreak())
                    if self.var.get() == 0:
                        page.append('Проверил:\n')
                    else:
                        page.append('Проверила:\n')
                    page.append(f'{str(self.entry6.get())}\n')

            # Нижний колонтитул
            header = PageStyle("header")
            with header.create(Foot("C")):
                header.append(f'Москва, {time.now().timetuple().tm_year}\n')
            doc.preamble.append(header)
            doc.change_document_style("header")

            doc.generate_pdf("title", clean_tex=False)
            self.status['text'] = 'Готово!'

        except FileNotFoundError as e:
            self.status['text'] = str(e)
Пример #24
0
def details():
    if __name__ == '__main__':


        image_filename = os.path.join(os.path.dirname(__file__), 'kitten.jpg')
        logo_file = os.path.join(os.path.dirname(__file__),'sample-logo.png')

        geometry_options = {"tmargin": "1cm", "lmargin": "3cm"}
        doc = Document(geometry_options=geometry_options)
        header = PageStyle("header")
        with header.create(Head("R")):
            header.append(simple_page_number())
        with header.create(Foot("C")):
            header.append("Center Footer")
        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')) as logo_wrapper

        with doc.create(MiniPage(align='l')):
            doc.append(LargeText(bold("INVESTMENT PROPERTY - BUY & HOLD")))
            doc.append(LineBreak())
            doc.append(MediumText(bold(" ")))
        logo_wrapper.append(StandAloneGraphic(image_options="width=120px",
                                              filename=logo_file))
        with doc.create(Section('Home Adress')):
            doc.append('Some regular text and some')
            doc.append(italic('italic text. '))
            doc.append('\nAlso some crazy characters: $&#{}')
            with doc.create(Subsection('Math that is incorrect')):
                doc.append(Math(data=['2*3', '=', 9]))

            with doc.create(Subsection('Table of something')):
                with doc.create(Tabular('rc|cl')) as table:
                    table.add_hline()
                    table.add_row((1, 2, 3, 4))
                    table.add_hline(1, 2)
                    table.add_empty_row()
                    table.add_row((4, 5, 6, 7))

        a = np.array([[100, 10, 20]]).T
        M = np.matrix([[2, 3, 4],
                       [0, 0, 1],
                       [0, 0, 2]])

        with doc.create(Section('The fancy stuff')):
            with doc.create(Subsection('Correct matrix equations')):
                doc.append(Math(data=[Matrix(M), Matrix(a), '=', Matrix(M * a)]))

            with doc.create(Subsection('Alignat math environment')):
                with doc.create(Alignat(numbering=False, escape=False)) as agn:
                    agn.append(r'\frac{a}{b} &= 0 \\')
                    agn.extend([Matrix(M), Matrix(a), '&=', Matrix(M * a)])

            with doc.create(Subsection('Beautiful graphs')):
                with doc.create(TikZ()):
                    plot_options = 'height=4cm, width=6cm, grid=major'
                    with doc.create(Axis(options=plot_options)) as plot:
                        plot.append(Plot(name='model', func='-x^5 - 242'))

                        coordinates = [
                            (-4.77778, 2027.60977),
                            (-3.55556, 347.84069),
                            (-2.33333, 22.58953),
                            (-1.11111, -493.50066),
                            (0.11111, 46.66082),
                            (1.33333, -205.56286),
                            (2.55556, -341.40638),
                            (3.77778, -1169.24780),
                            (5.00000, -3269.56775),
                        ]

                        plot.append(Plot(name='estimate', coordinates=coordinates))

            with doc.create(Subsection('Cute kitten pictures')):
                with doc.create(Figure(position='h!')) as kitten_pic:
                    kitten_pic.add_image(image_filename, width='120px')
                    kitten_pic.add_caption('Look it\'s on its back')

        doc.generate_pdf('full', clean_tex=False)
Пример #25
0
def get_document(document_title='Report',
                 author='Entail AS',
                 fig_ext=u'.pdf',
                 header_logofilename='entail.pdf',
                 logo_image_option_header="width=250px",
                 workflow_ID=0):
    global _fig_ext
    _fig_ext = fig_ext

    geometry_options = {
        "head": "70pt",
        "margin": "1.5cm",
        "bottom": "1.5cm",
        "includeheadfoot": True
    }
    document_options = ['a4paper']
    doc = Document(geometry_options=geometry_options,
                   document_options=document_options)

    # packages
    doc.packages.append(Package('booktabs'))
    doc.packages.append(Package('chngcntr'))
    doc.packages.append(Package('longtable'))
    doc.packages.append(Package('titlepic'))
    doc.packages.append(Package('float'))
    # 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.25\textwidth"),
                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(
                os.path.dirname(os.path.abspath(__file__)),
                header_logofilename).replace('\\', '/')
            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.75\textwidth"), pos='c',
                         align='r')) as title_wrapper:
            title_wrapper.append(LargeText(bold(document_title)))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold(NoEscape(r'\today'))))

    # Add footer
    with first_page.create(Foot("C")) as center_footer:
        center_footer.append(simple_page_number())
    with first_page.create(Foot("R")) as right_footer:
        with right_footer.create(
                MiniPage(width=NoEscape(r"0.15\textwidth"),
                         pos='r')) as logo_wrapper:
            logo_file = os.path.join(
                os.path.dirname(os.path.abspath(__file__)),
                'tailor.png').replace('\\', '/')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=50px",
                                  filename=logo_file))

    doc.preamble.append(first_page)
    doc.change_document_style("firstpage")
    doc.preamble.append(Command('title', document_title))
    logo_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             header_logofilename).replace('\\', '/')
    doc.preamble.append(
        Command(
            'titlepic',
            StandAloneGraphic(image_options=logo_image_option_header,
                              filename=logo_file)))
    # doc.preamble.append(Command('author', author))
    doc.preamble.append(Command('date', NoEscape(r'\today')))
    doc.preamble.append(
        Command(
            'hypersetup',
            arguments=
            'colorlinks, citecolor=black, filecolor=black, linkcolor=black, urlcolor=black',
            packages=[Package('hyperref')]))
    doc.preamble.append(NoEscape(r'\counterwithin{figure}{section}'))
    doc.append(NoEscape(r'\maketitle'))

    # Add disclaimer
    doc.append(NewPage())
    doc.append(NoEscape(r'\textbf{Disclaimer}'))
    doc.append(NoEscape(r'\newline'))
    doc.append(NoEscape(r'\vspace{0.2in}'))

    temptext = f'This is in automatically generated report. '
    if workflow_ID == 0:
        temptext += f'The report was generated '
    else:
        temptext += f'The results are extracted from Workflow ID {workflow_ID} '
    temptext += f'on the {datetime.datetime.now().strftime("%m/%d/%Y at %H:%M:%S")}. '
    temptext += f'Errors may occur and it is the user’s responsibility to interpret the reported data '
    temptext += f'with sound engineering judgement.'
    doc.append(temptext)

    doc.append(NewPage())
    doc.append(Command('tableofcontents'))
    doc.append(NewPage())

    return doc
Пример #26
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')
Пример #27
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')
Пример #28
0
    def generate(self):
        geometry_options = {
            "lmargin": "2.5cm",
            "rmargin": "2.5cm",
            "tmargin": "1cm"
        }
        doc = Document(geometry_options=geometry_options)
        doc.packages.append(Package('float'))
        with doc.create(Center()):
            doc.append(LargeText('Optimization Report'))
        with doc.create(Figure(position='H')) as plot:
            self.plot()
            plot.add_plot(width=NoEscape('17cm'))
        with doc.create(Section('Input:', False)):
            with doc.create(Itemize()) as input:
                input.add_item("Filenames:")
                with doc.create(Itemize()) as filenames:
                    for defmode in range(3):
                        if self.plot_defmode[defmode]:
                            filenames.add_item(self.titles[defmode] \
                                + ': ' + self.filenames[defmode])
                input.add_item("Weights:")
                with doc.create(Itemize()) as weights:
                    for defmode in range(3):
                        if self.plot_defmode[defmode]:
                            weights.add_item('{}: {:.4g}'.format( \
                                self.titles[defmode], self.weights[defmode]))
                input.add_item("Model: " + self.model.name)
                input.add_item("Error function: " + self.fit_error.name)
                input.add_item("Method: " + self.method.name)
                with doc.create(Itemize()) as methodparams:
                    for methodparam in self.method.print_params().split('\n'):
                        methodparams.add_item(methodparam)
        with doc.create(Section('Output:', False)):
            with doc.create(Itemize()) as output:
                s = '\\text{Errors: (}' + self.fit_error.name_latex + '\\text{)}'
                output.add_item(Math(inline=True, data=s, escape=False))
                with doc.create(Itemize()) as errorlist:
                    weighted_error = 0.0
                    for defmode in range(3):
                        if not self.plot_defmode[defmode]:
                            continue
                        error = self.fit_error(self.model.getfunc(defmode),
                                               self.model.getjac(defmode),
                                               self.model.gethess(defmode),
                                               self.xdatas[defmode],
                                               self.ydatas[defmode])
                        errval = error.objfunc(self.params)
                        weighted_error += errval * self.weights[defmode]
                        errorlist.add_item('{}: {:.4g}'.format(
                            self.titles[defmode], errval))
                    errorlist.add_item(
                        'Weighted: {:.4g}'.format(weighted_error))
                output.add_item('Parameters:')
                with doc.create(Itemize()) as parameters:
                    for pname, p in zip(self.model.paramnames_latex,
                                        self.params):
                        s = '{}: {:.4g}'.format(pname, p)
                        parameters.add_item(
                            Math(inline=True, data=s, escape=False))

        filename = os.path.splitext(self.filename)[0]
        doc.generate_pdf(filename, clean_tex=False, compiler='pdflatex')
Пример #29
0
from pylatex.utils import bold

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

# documnet_options = ["a4paper"] can also be used to set the paper size
doc = Document("paragraph", indent=True, geometry_options=geometry_options, document_options="a4paper");

text1 = """At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id.""";

text2 = """quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis olor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessit atibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.""";

text3 = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duisaute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla ariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum""";

with doc.create(Paragraph("")):
	doc.append(LargeText( bold("Dear Malinikesh,")));

with doc.create(Paragraph("Paragraph1")):
	doc.append(text1);

with doc.create(Paragraph("Paragraph2")):
	doc.append(text2);

with doc.create(Paragraph("")):
	doc.append(text3);

doc.generate_pdf(clean_tex=False)
Пример #30
0
import pickle
os.chdir(os.path.dirname('whatecer directory the file papers.dat is'))
with open("papers.dat", "rb") as fp:   # Unpickling
   papers = pickle.load(fp)


i = 0
for p in papers:
  doc = Document()
  doc.preamble.append(Command('title',p['TI']))
  doc.preamble.append(Command('author',';  '.join(p['FAU'])))
  doc.preamble.append(Command('date',p['EDAT']))
  #doc.append(NoEscape(r'\maketitle'))
  with doc.create(Section('A second section')):
    doc.append(NoEscape(r'\maketitle'))
    doc.append(LargeText(bold('Abstract\n\n')))
    doc.append('\n')
    doc.append(p['AB'])
    doc.append('\n\n\n\n')
    doc.append('Mesh Terms\n')
    if 'MH' in p:
      doc.append(p['MH'])
      doc.append('\n\n')
    doc.append(p['SO'])
    doc.append('\n\n')
    doc.append('PMID: ' + p['PMID'])
    doc.append('\n\n')
    if 'PMC' in p:
      doc.append('PMC: ' + p['PMC'])
    doc.generate_pdf(str(i+1), clean_tex=True)
    
Пример #31
0
doc.preamble.append(NoEscape(r'\usepackage[margin=1in]{geometry}'))
doc.preamble.append(NoEscape(r'\usepackage{hyperref}'))
doc.preamble.append(NoEscape(r'\hypersetup{colorlinks=true, linkcolor=blue, filecolor=magenta, urlcolor=cyan}'))
doc.preamble.append(NoEscape(r'\urlstyle{same}'))

doc.preamble.append(NoEscape(r'\linespread{1.6}'))

doc.preamble.append(Command('title','Trounceflow Countries: Argentina'))
doc.preamble.append(Command('author', 'Michael Trounce'))
doc.preamble.append(Command('date', NoEscape(r'\today')))
#doc.preamble.append(Command('footnote', 'The values presented in this report are the face values of the bonds'))
doc.append(NoEscape(r'\maketitle'))

doc.append(NoEscape(r'\begin{abstract}'))
doc.append("The `Trounceflow Countries' series of `living' documents provide real-time dynamic summaries of macroeconomic data relevant to the flows-and-positions analysis of emerging market debt. These macroeconomic data concentrate on the structure of the government bond market but also include other useful but hard-to-wrangle data such as the structure of the local institutional investor base. The data is obtained from the Trounceflow App (trounceflow.com) and the document data is automatically updated in line with the automatic updates on the App; links to the underlying national sources are also given in the `living' documents.")
doc.append(LargeText("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nThe values presented in this report are the face values of the bonds"))
doc.append(NoEscape(r'\end{abstract}'))
doc.append(NewPage())

doc.append(NoEscape(r'\tableofcontents'))
doc.append(NewPage())


#Summary Chapter 1
doc.append(NoEscape(r'\chapter{Executive Summary}'))
doc.append(NewPage())

#The recent data table
#central debt section 1.1 
with doc.create(Section('Central Government Debt')):
    with doc.create(Tabular('l|l|r|r')) as table: