def create_adventure(filename: str, title_model: markovify.Text,
                     chapter_model: markovify.Text,
                     heading_model: markovify.Text,
                     spoken_model: markovify.Text,
                     paragraph_model: markovify.Text):
    doc = Document()
    doc.documentclass = Command(
        'documentclass',
        options="letterpaper,twocolumn,openany,nodeprecatedcode",
        arguments=["dndbook"])
    doc.preamble.append(Command('title', title_model.make_sentence()))
    doc.append(NoEscape(r'\maketitle'))
    doc.append(NoEscape(r'\tableofcontents'))
    for _ in range(random.randint(5, 12)):
        with doc.create(chapter(chapter_model.make_sentence())):
            for _ in range(random.randint(5, 15)):
                heading = heading_model.make_sentence()
                while heading is None:
                    heading = heading_model.make_sentence()
                with doc.create(Section(heading)):
                    with doc.create(DndReadAloud()):
                        doc.append(spoken_model.make_sentence())
                    for _ in range(3, 9):
                        doc.append(paragraph_model.make_sentence())
    doc.generate_tex(filename)
예제 #2
0
    def _generiraj_latex_dokument(self, delovni_list: DelovniList):
        latex_dokument = Document()
        # Dokumentu nastavimo razred `izpit`, ki vsebuje ukaze za naloge,
        # primere in podobno.
        latex_dokument.documentclass = Command('documentclass', 'izpit')

        # Dokument je potrebno zaceti z ukazmo izpit, ki mu dodamo naslov in
        # opis (navodila) delovnega lista.
        ukaz_izpit = Command('izpit',
                             arguments=[
                                 remove_newlines(delovni_list.naslov), '',
                                 remove_newlines(delovni_list.opis)
                             ],
                             options=Options(naloge=0))
        latex_dokument.append(ukaz_izpit)

        # Ko smo dodali ukaz za izpit, se sprehodimo cez vse naloge in
        # generiramo latex zanje
        for naloga in delovni_list.naloge.all():
            # Generiramo ukaze za doloceno nalogo
            naloga_ukazi = self.generiraj_latex_za_nalogo(
                naloga, latex_dokument)
            # Dodamo ukaze v latex dokument
            latex_dokument.extend(naloga_ukazi)

        return latex_dokument
예제 #3
0
def generate_document(parts):
    # set language to german, e.g. used for strftime()
    locale.setlocale(locale.LC_TIME, "de_CH.utf8")

    # create basic document
    geometry_options = {
        "left": "2.5cm",
        "right": "2.5cm",
        "top": "3cm",
        "bottom": "3cm"
    }
    document = Document(inputenc='utf8x',
                        lmodern=True,
                        geometry_options=geometry_options)
    document.documentclass = Command(
        'documentclass',
        options=['11pt', 'a4paper'],
        arguments=['article'],
    )

    # globally packages
    document.packages.add(Package('babel', options='german'))

    # camp object that stores the exported date
    camp = Camp('WRhzcGYImUWC1DV3MPaf', 'CKsbjuHkJQUstW1YULeAepDe9Wl1')

    # add sections according to export settings
    for part in parts:
        logging.log(logging.INFO, 'append ' + part.__name__)
        part(document, camp)
        document.append(NoEscape(r'\newpage'))

    return document
예제 #4
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')
예제 #5
0
    def _construct_latex_document(self, output_path):
        # Create an output document
        latex_document = Document(output_path, fontenc=None)

        # Use plari document class
        latex_document.documentclass = Command(
            'documentclass',
            arguments=['plari']
        )

        return latex_document
예제 #6
0
    def _construct_latex_document(self, output_path):
        # Create an output document
        latex_document = Document(output_path, fontenc=None)

        # TODO: set fixed path to drama.cls
        # Use custom document class - drama.cls
        latex_document.documentclass = Command(
            'documentclass',
            arguments=['drama']
        )

        return latex_document
예제 #7
0
def generate_pdf():
    global questions, answers, test

    geometry_options = {"tmargin": "0.5cm"}
    doc = Document('basic', geometry_options=geometry_options)
    doc.documentclass = Command(
        'documentclass',
        options=['12pt'],
        arguments=['exam'],
    )

    doc.preamble.append(Command('title', str(test)))
    doc.preamble.append(Command('author', str(test.course)))
    doc.preamble.append(Command('date', NoEscape(r'\today')))
    doc.append(NoEscape(r'\maketitle'))
    doc.append(
        NoEscape(
            r'\hbox to \textwidth{Name:\enspace\hrulefill\hrulefill\hrulefill\enspace '
            + 'Date:\enspace\hrulefill}'))

    doc.append(NoEscape(r'\vspace{0.1in}'))
    doc.append(NoEscape(r'\begin{center}'))
    doc.append(
        NoEscape(
            r'\fbox{\fbox{\parbox{5.5in}{Answer the questions in the spaces provided on '
            +
            'the question sheets. If you run out of room for an answer, continue on the back of the page.}}}'
        ))
    doc.append(NoEscape(r'\addpoints'))
    doc.append(NoEscape(r'\bigskip'))
    doc.append(NoEscape(r'\newline'))
    doc.append(NoEscape(r'\gradetable[h][questions]'))
    doc.append(NoEscape(r'\bigskip'))
    doc.append(NoEscape(r'\end{center}'))

    doc.append(NoEscape(r'\begin{questions}'))
    for q in questions:
        doc.append(NoEscape(r'\question[1]  ' + str(q)))
        doc.append(NoEscape(r'\begin{choices}'))
        for a in answers:
            if a.question == q:
                doc.append(NoEscape(r'\choice ' + a.title))
        doc.append(NoEscape(r'\end{choices}'))
    doc.append(NoEscape(r'\end{questions}'))

    doc.generate_pdf(os.path.join(BASE_DIR, 'squizer/static/' + str(test.id)),
                     clean_tex=False)
예제 #8
0
    def generateExam(self):

        doc = Document('basic')
        doc.documentclass = Command(
            'documentclass',
            options=['12pt'],
            arguments=['exam'],
        )

        doc.packages.append(Package('amsmath'))
        doc.preamble.append(Command('pagestyle', 'headandfoot'))
        doc.preamble.append(
            Command(
                'firstpageheader',
                NoEscape(
                    r"""%s : %s \\ \today}{}{Name: \underline{\hspace{2.5in}}"""
                    % (self.course, self.subject))))

        doc.append(
            Command(
                'center',
                Command(
                    'fbox',
                    Command('fbox', 'NO CALCULATORS OR EXTERNAL RESOURCES'))))
        doc.append(Command('begin', 'questions'))

        for mcq in self.mcqs:
            doc.append(NoEscape(r'\question ' + mcq.prompt))
            doc.append(Command('begin', 'checkboxes'))
            for ans in mcq.answers:
                doc.append(Command('choice', ans))

        for frq in self.frqs:
            doc.append(NoEscape(r'\question ' + NoEscape(frq.prompt)))
            doc.append(Command('vspace', frq.spacing + 'in'))

        doc.append(Command('end', 'questions'))

        big_code = pyqrcode.create(np.array_str(self.answerKey), mode='binary')
        big_code.png('code.png')

        with doc.create(Figure(position='b!')) as code:
            code.add_image('code.png', width='50px')

        doc.generate_pdf(clean_tex=False, compiler='pdfLaTeX')
        doc.generate_tex()
예제 #9
0
    'type': 'input',
    'name': 'answer',
    'message': 'Enter an incorrect answer:',
    'when': lambda answer: answer['add']
}]

if __name__ == '__main__':
    if prompt(mode)['mode'] == 'Create':

        header = prompt(headerQuestions, style=style)

        # Basic document
        doc = Document('basic')
        doc.documentclass = Command(
            'documentclass',
            options=['12pt'],
            arguments=['exam'],
        )

        doc.packages.append(Package('amsmath'))
        doc.preamble.append(Command('pagestyle', 'headandfoot'))
        doc.preamble.append(
            Command(
                'firstpageheader',
                NoEscape(
                    r"""%s : %s \\ \today}{}{Name: \underline{\hspace{2.5in}}"""
                    % (header['course'], header['material']))))

        doc.append(
            Command(
                'center',
예제 #10
0
def generate_recipes_pdf(recipes, pdf_opts, display_opts, ingredient_df):
    """ Generate a .tex and .pef from the recipes given
    recipes is an ordered list of RecipeTuple namedtuples
    """

    print "Generating {}.tex".format(pdf_opts.pdf_filename)
    pylatex.config.active = pylatex.config.Version1(indent=False)

    # Determine some settings based on the number of cols
    if pdf_opts.ncols == 1:
        side_margin = '1.75in'
        colsep = '44pt'
    elif pdf_opts.ncols == 2:
        side_margin = '0.8in'
        colsep = '50pt'
    elif pdf_opts.ncols == 3:
        side_margin = '0.5in'
        colsep = '44pt'
    else:
        side_margin = '0.5in'
        colsep = '30pt'

    # Document setup
    doc_opts = {
        'geometry_options': {
            'showframe': pdf_opts.debug,
            'left': side_margin,
            'right': side_margin,
            'top': '0.4in',
            'bottom': '0.2in',
            'headheight': '29pt',
            'includehead': True,
            'includefoot': True,
        }
    }
    doc = Document(**doc_opts)
    doc.documentclass = Command('documentclass',
                                options=Options('11pt', 'portrait',
                                                'letterpaper'),
                                arguments=Arguments('article'))

    # http://www.tug.dk/FontCatalogue/computermoderntypewriterproportional/
    doc.preamble.append(
        Command(r'renewcommand*\ttdefault', extra_arguments='cmvtt'))
    doc.preamble.append(
        Command(r'renewcommand*\familydefault',
                extra_arguments=NoEscape(r'\ttdefault')))

    # apply a header and footer to the document
    setup_header_footer(doc, pdf_opts, display_opts)

    # Columns setup and fill
    paracols = add_paracols_environment(doc,
                                        pdf_opts.ncols,
                                        colsep,
                                        sloppy=False)
    for i, recipe in enumerate(recipes, 1):
        paracols.append(format_recipe(recipe, display_opts))
        switch = 'switchcolumn'
        if pdf_opts.align:
            switch += '*' if (i % pdf_opts.ncols) == 0 else ''
        paracols.append(Command(switch))

    # append a page on the ingredients
    if pdf_opts.liquor_list or pdf_opts.liquor_list_own_page:
        append_liquor_list(doc,
                           ingredient_df,
                           own_page=pdf_opts.liquor_list_own_page)

    print "Compiling {}.pdf".format(pdf_opts.pdf_filename)
    doc.generate_pdf(pdf_opts.pdf_filename, clean_tex=False)
    print "Done"
    return True
예제 #11
0
def PyLaTex_generator(title, section1, section1Title, section2, section2Title,
                      section3, section3Title, path, includeImages):

    now = datetime.datetime.now()

    # Defines the file folder path and the dependences folder path
    filepath = (path + r"/OUTPUT")
    if (os.path.isdir(filepath) == False):
        os.makedirs(filepath)

    dependencesPath = (path + r"/DEPENDENCES")
    if (os.path.isdir(dependencesPath) == False):
        os.makedirs(dependencesPath)

    # Write the LaTex report
    doc = Document(filepath)
    doc.documentclass = Command(
        'documentclass',
        options=['brazilian', '12pt', 'oneside', 'a4paper'],
        arguments=['article'],
    )

    doc.preamble.append(NoEscape(r'\input{DEPENDENCES/preamble.tex}'))
    doc.preamble.append(Command('titulo', {title}))
    doc.preamble.append(NoEscape(r'\data{\today}'))
    doc.append(NoEscape(r'\setFaixa'))
    doc.append(NoEscape(r'\geraTitulo'))
    doc.append(NoEscape(r'\section{' + section1Title + '}'))
    doc.append(section1)
    doc.append(NoEscape(r'\section{' + section2Title + '}'))
    doc.append(section2)
    doc.append(NoEscape(r'\section{' + section3Title + '}'))
    doc.append(section3)

    # Include all images in the report
    if (includeImages == True and os.path.isdir(path + r"/IMAGES") == True):
        doc.append(NoEscape(r'\section{Dados}'))
        c = 1
        imageComand = ""
        imagesPath = path + r"/IMAGES"

        for image in os.listdir(imagesPath):

            if image == "map.png":
                doc.append(
                    NoEscape(r"""
    \begin{figure}[htb]
        \centering
            \includegraphics[scale=0.30]{""" + r"IMAGES/" + image + r"""}
            \caption{Trajetória da sonda sobre o região de São Carlos}    
    \end{figure}
            """))

            elif image == "Map.html":
                pass

            else:
                if os.path.isfile(os.path.join(imagesPath, image)):
                    splittedGraphName = re.split("_", image[:-4])
                    caption = f"Gráfico {splittedGraphName[1]} versus {splittedGraphName[3]}"
                    if c == 4:
                        imageComand = imageComand + r"    \subfloat[" + caption + r"]{\includegraphics[width = 1.5in]{" + r"IMAGES/" + image + r"}}\\" + "\n"
                        c = 1
                    else:
                        imageComand = imageComand + r"    \subfloat[" + caption + r"]{\includegraphics[width = 1.5in]{" + r"IMAGES/" + image + r"}} &" + "\n"
                        c = c + 1

        doc.append(
            NoEscape(r"""
    \begin{figure}[htb]
        \centering
            \begin{tabular}{cccc}
        """ + "\n" + imageComand + r"""
            \end{tabular}
            \caption{Gráficos}    
    \end{figure}
            """))

    filename = (r"zenith_report_{dia}-{mes}-{ano}".format(dia=now.day,
                                                          mes=now.month,
                                                          ano=now.year))
    doc.generate_tex(r"{filepath}/{filename}".format(filepath=filepath,
                                                     filename=filename))

    # Copy dependence files
    shutil.copy(
        os.path.join(os.path.dirname(os.path.abspath(__file__)),
                     "DEPENDENCES/preamble.tex"), dependencesPath)
    shutil.copy(
        os.path.join(os.path.dirname(os.path.abspath(__file__)),
                     "DEPENDENCES/IMAGES/LogoZ.png"), dependencesPath)
    shutil.copy(
        os.path.join(os.path.dirname(os.path.abspath(__file__)),
                     "DEPENDENCES/IMAGES/zenith-faixa.png"), dependencesPath)

    # make_archive(filename, path, path + "/" + filename + ".zip")

    # Creates a zip file
    directoriesList = [
        path + "/DEPENDENCES", path + "/IMAGES", path + "/OUTPUT"
    ]
    zip_files(directoriesList, path + "/" + filename + ".zip")
예제 #12
0
    def generate_report(self):
        # Basic document
        # Document with `\maketitle` command activated
        doc = Document(default_filepath=(self.folder + r"/figures"))
        doc.documentclass = Command(
            'documentclass',
            options=['10pt', 'a4'],
            arguments=['article'],
        )
        doc.packages.append(NoEscape(r'\setcounter{tocdepth}{4}'))
        doc.packages.append(NoEscape(r'\setcounter{secnumdepth}{1}'))
        # usepackages
        doc.packages.append(Package('helvet'))
        doc.packages.append(Package('graphicx'))
        doc.packages.append(Package('geometry'))
        doc.packages.append(Package('float'))
        doc.packages.append(Package('amsmath'))
        doc.packages.append(Package('multicol'))
        doc.packages.append(Package('ragged2e'))
        doc.packages.append(Package('breakurl'))
        doc.packages.append(Package('booktabs, multirow'))
        doc.packages.append(Package('epstopdf'))
        doc.packages.append(
            NoEscape(r'\usepackage[nolist, nohyperlinks]{acronym}'))
        doc.packages.append(Package('hyperref'))

        # add commands
        doc.preamble.append(
            NoEscape(r"\renewcommand{\familydefault}{\sfdefault}"))
        doc.preamble.append(
            NoEscape(r"\newcommand\Tstrut{\rule{0pt}{3ex}}  % = `top' strut"))
        doc.preamble.append(
            NoEscape(
                r"\newcommand\Bstrut{\rule[1ex]{0pt}{0pt}}   % = `bottom' strut"
            ))

        # make title
        title = "Report for Session: " + self.session
        doc.preamble.append(Command('title', title))
        #doc.preamble.append(Command('author', 'Anonymous author'))
        doc.preamble.append(Command('date', NoEscape(r'\today')))
        doc.append(NoEscape(r'\maketitle'))
        doc.append(NoEscape(r'\tableofcontents'))
        doc.append(NewPage())
        doc.append(
            NoEscape(r'\newgeometry{vmargin={12mm}, hmargin={10mm,10mm}}'))
        doc.append(NoEscape(r'\bigskip'))

        # summary section
        with doc.create(Section('Session summary')):
            # create summary table
            with doc.create(LongTabu("X | X")) as summary_table:
                with doc.create(Tabular("r r")) as small_table:
                    small_table.add_row(["Summary", ""])
                    small_table.add_hline()
                    small_table.add_row(["Gamble side:", self.gamble_side])
                    small_table.add_hline()
                    small_table.add_row(
                        ["All trials",
                         self.all_trials_df.index.max()])
                    small_table.add_row(
                        ["Good trials",
                         self.good_trials_df.index.max()])
                    small_table.add_row([
                        "Selected trials",
                        self.selected_trials_df.index.max()
                    ])
                    small_table.add_hline()
                    small_table.add_row([
                        "Probability bins",
                        str(self.all_trials_df['probability'].unique())
                    ])

                # add overview plots
                doc.append(NoEscape(self.image_box("hist_fit", last=True)))
                doc.append(NoEscape(self.image_box("trial_length")))
                doc.append(NoEscape(self.image_box("cluster_hist", last=True)))
                doc.append(NewPage())

        # Add stuff to the document
        with doc.create(
                Section('Spike Trains and Histogram for Reward Events')):
            # create necessary variables
            for cluster in self.clusters_df.loc[self.clusters_df['group'] ==
                                                'good'].index:
                # create subsection title
                subsection = "Cluster " + str(cluster)
                with doc.create(Subsection(subsection, label=False)):
                    # create details table
                    with doc.create(LongTabu("X | X")) as details_table:

                        doc.append(
                            NoEscape(self.image_box_cluster("isi", cluster)))
                        doc.append(
                            NoEscape(
                                self.image_box_cluster("spk_train",
                                                       cluster,
                                                       last=True)))
                        details_table.add_hline()
                        details_table.add_row(
                            ["All Trials", "Rewarded Trials"])
                        doc.append(
                            NoEscape(
                                self.image_box_cluster(
                                    "spk_train_hist_all-events", cluster)))
                        doc.append(
                            NoEscape(
                                self.image_box_cluster(
                                    "spk_train_hist_all-events_reward-centered",
                                    cluster,
                                    last=True)))
                        details_table.add_hline()
                        details_table.add_row(
                            ["Gambl Side Reward", "Save Side Reward"])
                        #details_table.end_table_header()
                        doc.append(
                            NoEscape(
                                self.image_box_cluster(
                                    "spk_train_hist_gamble_reward", cluster)))
                        doc.append(
                            NoEscape(
                                self.image_box_cluster(
                                    "spk_train_hist_save_reward",
                                    cluster,
                                    last=True)))
                        #details_table.add_hline()
                        details_table.add_row(
                            ["Gambl Side No-Reward", "Save Side No-Reward"])
                        doc.append(
                            NoEscape(
                                self.image_box_cluster(
                                    "spk_train_hist_gamble_no-reward",
                                    cluster)))
                        doc.append(
                            NoEscape(
                                self.image_box_cluster(
                                    "spk_train_hist_save_no-reward",
                                    cluster,
                                    last=True)))
                doc.append(NewPage())

        # create file_name
        filepath = (self.folder + "/" + self.session + "-report")
        # create pdf
        doc.generate_pdf(
            filepath, clean=True, clean_tex=True
        )  #, compiler='latexmk -f -xelatex -interaction=nonstopmode')
예제 #13
0
        print("Finished parsing row {}".format(v))
        print(wanted_bul)

    elif sheet.acell('A{}'.format(i)).value == "Stop":
        print("Finished parsing")

'''
Latex Section Begins:
'''

for i in range(2, 5):
    if __name__ == '__main__':
        v = i - 1
        doc = Document()
        doc.documentclass = Command('documentclass', options=['12pt'], arguments=['article'])
        doc.packages.append(pyl.Package('graphicx'))
        doc.packages.append(pyl.Package('fancyhdr'))
        doc.packages.append(pyl.Package('float'))

        doc.preamble.append(pyl.Command('pagestyle', 'fancy'))
        doc.preamble.append(pyl.Command('title', 'Notebook'))
        doc.append(date[v] + " - " + author[v])

        with doc.create(Section('Our Plan')):
            with doc.create(Itemize()) as itemize:
                for item in wanted_bul[v]:
                    itemize.add_item(item)
            doc.append(wanted_par[v])
        with doc.create(Section('What We Got Done')):
            with doc.create(Itemize()) as itemize:
예제 #14
0
from zipfile import ZipFile
import os
from os.path import basename

now = datetime.datetime.now()

titulo = "Título de meu arquivo"
resumo = "Resumo de meu arquivo"
conteudo = "Conteúdo de meu arquivo"
conclusao = "Conclusão de meu arquivo"

filepath = (r"latex_generator\output")
doc = Document(filepath)
doc.documentclass = Command(
    'documentclass',
    options=['brazilian', '12pt', 'oneside', 'a4paper'],
    arguments=['article'],
)

doc.preamble.append(NoEscape(r'\input{preamble.tex}'))
doc.preamble.append(Command('titulo', {titulo}))
doc.preamble.append(NoEscape(r'\data{\today}'))
doc.append(NoEscape(r'\setFaixa'))
doc.append(NoEscape(r'\geraTitulo'))
doc.append(NoEscape(r'\section{Resumo}'))
doc.append(resumo)
doc.append(NoEscape(r'\section{Conteúdo}'))
doc.append(conteudo)
doc.append(NoEscape(r'\section{Conclusão}'))
doc.append(conclusao)
doc.append(NoEscape(r'\section{Dados}'))
예제 #15
0
    def topdf(self,pdfname=None):

        if pdfname is None:
            pdfname = self.pdfname

        filename = pdfname[:-4]

        geometry_options = {"margin": "2cm"}
        doc = Document(
                default_filepath=filename,
                geometry_options=geometry_options
                )
        doc.documentclass = Command(
                'documentclass',
                options=['12pt','landscape'],
                arguments=['article'],
                )

        doc.packages.append(Package('fancyhdr'))
        for group in self.grouplist:
            doc.preamble.append(NoEscape(r'\fancypagestyle{{{0}}}{{\fancyhf{{}}\fancyhead[L]{{\textbf{{{1}/{2}}}}}\fancyhead[R]{{{3}}}\fancyfoot[R]{{Page\ \thepage\ of \pageref{{LastPage}}}}}}'.format(group.name.replace('_',''),self.case,self.subcase,group.head)))

        width = 0.25 #min(int(0.9/nplot*100.)/100.,0.25)
        nplot_per_line = 4

        for group in self.grouplist:
            doc.append(NoEscape(r'\pagestyle{{{0}}}'.format(group.name.replace('_',''))))
            all2D = True
            all1D = True
            for diag in group.diaglist:
                all2D = all2D and (diag.diag_type == 'plot2D')
                all1D = all1D and ((diag.diag_type == 'plotTS') or (diag.diag_type == 'plotAvgP') or\
                                   (diag.diag_type == 'plotInitP'))

            if all2D:
                for diag in group.diaglist:
                    header = PageStyle("header")
                    keys = diag.output.keys()
                    nplot = len(keys)
                    nlines = nplot/nplot_per_line
                    for i in range(0,nlines+1):
                        with doc.create(Figure(position='h!')) as fig:
                            for j in range(0,nplot_per_line):
                                if i*nplot_per_line+j < nplot:
                                    with doc.create(SubFigure(
                                        position='b',
                                        width=NoEscape(r'{0}\linewidth'.format(width)))
                                        ) as subfig:
                                        subfig.add_image(diag.output[keys[i*nplot_per_line+j]],width=NoEscape(r'\linewidth'))
                    if nlines > 0:
                        doc.append(NoEscape(r'\clearpage'))

            elif all1D:
                nplot = len(group.diaglist)
                nlines = nplot/nplot_per_line
                for i in range(0,nlines+1):
                    with doc.create(Figure(position='h!')) as fig:
                        for j in range(0,nplot_per_line):
                            if i*nplot_per_line+j < nplot:
                                with doc.create(SubFigure(
                                    position='b',
                                    width=NoEscape(r'{0}\linewidth'.format(width)))
                                    ) as subfig:
                                    subfig.add_image(group.diaglist[i*nplot_per_line+j].output,width=NoEscape(r'\linewidth'))

            else:
                print 'ERROR: mixed case not coded yet'
                raise ValueError

            doc.append(NoEscape(r'\clearpage'))

        doc.generate_pdf(clean_tex=True)

        os.system('mv {0}.pdf {1}/'.format(filename,self.pdf_dir))
예제 #16
0
def processLaTex():

    titlePage = r'''
\renewcommand{\maketitle}{%

	\begin{titlepage} % Suppresses headers and footers on the title page

	\centering % Centre everything on the title page
	
	\scshape % Use small caps for all text on the title page
	
	\vspace*{\baselineskip} % White space at the top of the page
	
	%------------------------------------------------
	%	Title
	%------------------------------------------------
	
	\rule{\textwidth}{1.6pt}\vspace*{-\baselineskip}\vspace*{2pt} % Thick horizontal rule
	\rule{\textwidth}{0.4pt} % Thin horizontal rule
	
	\vspace{0.75\baselineskip} % Whitespace above the title
	
	{\LARGE THE DICTIONARY \\ OF COLLECTED WORDS\\} % Title
	
	\vspace{0.75\baselineskip} % Whitespace below the title
	
	\rule{\textwidth}{0.4pt}\vspace*{-\baselineskip}\vspace{3.2pt} % Thin horizontal rule
	\rule{\textwidth}{1.6pt} % Thick horizontal rule
	
	\vspace{2\baselineskip} % Whitespace after the title block
	
	%------------------------------------------------
	%	Subtitle
	%------------------------------------------------
	
	A Number of Fascinating and Fundamental Words Presented in a Dictionary Way % Subtitle or further description
	
	\vspace*{3\baselineskip} % Whitespace under the subtitle
    \vspace*{3\baselineskip} % Whitespace under the subtitle
    \vspace*{3\baselineskip} % Whitespace under the subtitle
	
	%------------------------------------------------
	%	Editor(s)
	%------------------------------------------------
	
	Edited By
	
	\vspace{0.5\baselineskip} % Whitespace before the editors
	
	{\scshape\Large Arafat Hasan \\} % Editor list
	
	\vspace{0.5\baselineskip} % Whitespace below the editor list
	
	\textit{Mawlana Bhashani Science and Technology University \\ Tangail, Bangladesh} % Editor affiliation
	
	\vfill % Whitespace between editor names and publisher logo
	
	%------------------------------------------------
	%	Publisher
	%------------------------------------------------
	
	%\plogo % Publisher logo
	
	%\vspace{0.3\baselineskip} % Whitespace under the publisher logo
	
	\the\year % Publication year
	
	%{\large publisher} % Publisher

	\end{titlepage}
}
'''

    pdfMeta = r'''
\usepackage[xetex,
            pdfauthor={Arafat Hasan},
            pdftitle={The Dictionary of Collected Words},
            pdfsubject={A Personal Dictionary},
            pdfkeywords={Personal Dictionary},
            pdfproducer={XeLaTeX on Ubuntu},
            pdfcreator={XeLaTeX}]{hyperref}
   '''


    geometry_options = {"top":"2.3cm","bottom":"2.0cm", "left":"2.5cm",\
            "right":"2.0cm", "columnsep":"27pt"}
    doc = Document('TheDictionaryOfCollectedWords',
                   geometry_options=geometry_options)
    doc.documentclass = Command(
        'documentclass',
        options=['10pt', 'a4paper', 'twoside'],
        arguments=['book'],
    )

    doc.packages.append(Package('palatino'))
    doc.packages.append(Package('microtype'))
    doc.packages.append(Package('multicol'))
    doc.packages.append(Package('fontspec'))
    doc.packages.append(Package('enumitem'))
    doc.packages.append(Package('graphicx'))
    doc.packages.append(Package('PTSerif'))
    doc.packages.append(Package('titlesec', NoEscape('bf, sf, center')))
    doc.packages.append(Package('fancyhdr'))


    doc.preamble.append(Command('usepackage', \
            NoEscape(r'xcolor'), 'svgnames'))

    doc.preamble.append(NoEscape(pdfMeta))
    doc.preamble.append(NoEscape('%'))
    doc.preamble.append(NoEscape('%'))

    doc.preamble.append(Command('setmainfont', \
            'TeX Gyre Pagella', 'Numbers=OldStyle'))


    doc.preamble.append(Command('fancyhead', \
            NoEscape(r'\textsf{\rightmark}'), 'L'))
    doc.preamble.append(Command('fancyhead', \
            NoEscape(r'\textsf{\leftmark}'), 'R'))

    doc.preamble.append(NoEscape('%'))
    doc.preamble.append(NoEscape('%'))

    doc.preamble.append(Command('renewcommand', \
        arguments=Arguments(NoEscape(r'\headrulewidth'), '1.4pt')))

    doc.preamble.append(Command('fancyfoot', \
            NoEscape(r'\textbf{\textsf{\thepage}}'), 'C'))

    doc.preamble.append(Command('renewcommand', \
        arguments=Arguments(NoEscape(r'\footrulewidth'), '1.4pt')))

    doc.preamble.append(Command('pagestyle', 'fancy'))

    doc.append(NoEscape(r'\setlength{\parindent}{-0.7em}'))

    new_comm = UnsafeCommand('newcommand', '\entry', options=7, \
    extra_arguments=NoEscape(r'\textbf{#1}\markboth{#1}{#1}\ {{\fontspec{Doulos SIL} #2}}\  {{\fontspec{Kalpurush} \small {#3}}}\ {#4}\ {#5}\ {\textit{#6}}\ {#7}'))
    doc.preamble.append(new_comm)

    color_bullet = UnsafeCommand('newcommand', '\colorBulletS', options=1, \
    extra_arguments=NoEscape(r'\colorbox[RGB]{171,171,171}{\makebox(11,2){\textcolor{white}{{\tiny \textbf{#1}}}}}'))
    doc.preamble.append(color_bullet)

    color_bullet = UnsafeCommand('newcommand', '\colorBullet', options=1, \
    extra_arguments=NoEscape(r'\colorbox[RGB]{171,171,171}{\makebox(22, 1){\textcolor{white}{{\tiny \textbf{#1}}}}}'))
    doc.preamble.append(color_bullet)

    doc.preamble.append(
        NoEscape(
            r'\newcommand{\plogo}{\fbox{$\mathcal{PL}$}} % Generic dummy publisher logo'
        ))

    doc.preamble.append(NoEscape('%'))
    doc.preamble.append(NoEscape('%'))

    doc.preamble.append(NoEscape(titlePage))
    doc.append(NoEscape(r'\maketitle'))
    entriesList = list(fileData.keys())
    entriesList.sort()

    currentSection = "a"
    sectionStr = "\chapter*{" + currentSection.upper() + "}"
    doc.append(NoEscape(sectionStr))
    doc.append(NoEscape(r'\begin{multicols}{2}'))

    for item in entriesList:
        entryList = fileData[item]
        for entry in entryList:
            word = entry.get('word', "")
            bengali = entry.get('bengali', "")
            prep = entry.get('prep', "")
            ownExample = entry.get('example', "")
            origin = entry.get('origin', "")
            phonetic = entry.get('phonetic', "")
            meaning = entry.get('meaning', {})

            word = escape_latex(word)
            bengali = escape_latex(bengali)
            prep = escape_latex(prep)
            ownExample = escape_latex(ownExample)
            origin = escape_latex(origin)
            phonetic = escape_latex(phonetic)

            if len(prep): prep = " \\colorBullet{OTHER} " + prep
            if len(origin): origin = " \\colorBullet{ORIGIN} " + origin

            partsOfSpeech = list(meaning.keys())

            if len(partsOfSpeech) == 1:
                partStr = ""
            else:
                partStr = "\\small{\\textsf{\\textit{" + escape_latex(
                    ", ".join(partsOfSpeech)) + "}}}"

            for part in partsOfSpeech:
                escapePart = escape_latex(str(part))
                onepart = meaning[part]
                deffCnt = 0
                if len(partsOfSpeech) == 1:
                    strGen = "\\textsf{\\textit{" + escapePart + "}}\\"
                else:
                    strGen = "\\\\{\\fontspec{DejaVu Sans}▪ }\\textsf{\\textit{" + escapePart + "}}\\\\"

                for deff in onepart:
                    deffCnt = deffCnt + 1
                    definition = deff.get('definition', "")
                    example = deff.get('example', "")
                    synonyms = deff.get('synonyms', {})

                    definition = escape_latex(definition)
                    example = escape_latex(example)
                    synonyms = escape_latex(", ".join(synonyms))
                    if len(synonyms):
                        synonyms = " \\colorBulletS{SYN} " + synonyms

                    strGen = strGen + " \\textbf{" + str(
                        deffCnt
                    ) + "} " + definition + " {\\fontspec{DejaVu Sans}◇} " + "\\textit{" + example + "}" + synonyms

                partStr = partStr + " " + strGen

            # lorem = "\entry{"+word+"}{"+phonetic+"}{"+bengali+"}{"+partStr+"}" + "{" + prep +"}" + "{" + ownExample + "}" + "{" + origin + "}" // With origin
            lorem = "\entry{" + word + "}{" + phonetic + "}{" + bengali + "}{" + partStr + "}" + "{" + prep + "}" + "{" + ownExample + "}"
            if item[0] is not currentSection[0]:
                currentSection = item[0]
                sectionStr = "\section*{" + currentSection.upper() + "}"
                doc.append(NoEscape(r'\end{multicols}'))
                doc.append(NoEscape(r'\pagebreak'))
                doc.append(NoEscape(sectionStr))
                doc.append(NoEscape(r'\begin{multicols}{2}'))
            doc.append(NoEscape(lorem))
            doc.append(NoEscape(r'\par'))

    doc.append(NoEscape(r'\end{multicols}'))
    doc.generate_pdf(clean_tex=False, compiler='xelatex')
    doc.generate_tex()

    tex = doc.dumps()