Exemplo n.º 1
0
    def _generiraj_nalogo_razvrsti_v_preglednico(self, naloga, latex_dokument):

        primeri_naloge = naloga.primeri()

        imena_skupin = primeri_naloge[0]['skupine']
        nastavitve_tabele = ['p{4cm}' for skupina in imena_skupin]

        center = Center()
        with center.create(Tabular('|{}|'.format(
                '|'.join(nastavitve_tabele)))) as tabela:
            tabela.add_hline()
            tabela.add_row(tuple(imena_skupin))
            tabela.add_hline()
            tabela.add_row(
                tuple([Command('vspace', arguments=['4cm'])] *
                      len(imena_skupin)))
            tabela.add_hline()

        primeri = []
        for primer in primeri_naloge:
            primeri.append(Command('podnaloga'))
            primeri.extend([', '.join(primer['besede'])])
            primeri.append(Command('vspace', ['0.5cm']))
            primeri.append(center)
            primeri.append(Command('vspace', ['0.5cm']))

        return primeri
Exemplo n.º 2
0
def configuracoes_preambulo(doc):
    doc.preamble.append(
        Command('setmainfont', 'TeX Gyre Heros',
                ['Scale=0.9', 'Ligatures=TeX']))

    doc.preamble.append(Command(
        'MakeOuterQuote',
        '\"'))  # coverte aspas automaticamente, sem precisar de `` e ''

    # Diretório das imagens
    img_dir = '{}/base/static/img/'.format(
        BASE_DIR)  # necessário barra no final
    doc.preamble.append(UnsafeCommand('graphicspath',
                                      '{{{}}}'.format(img_dir)))

    # Configuração das listas
    # TODO: substituir por enumeration_symbol
    doc.preamble.append(
        NoEscape(r'''
\setlist[enumerate, 1]{label*=\textbf{\arabic*}, leftmargin=*}
\setlist[enumerate, 2]{label*=\textbf{.\arabic*}, leftmargin=*}
    '''))

    # Configuração dos cabeçalhos
    doc.preamble.append(Command('pagestyle', 'fancy'))
Exemplo n.º 3
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
 def addPic(self):
     """
     This function can randomly insert an image
     with random size
     The image can be either single-row or across two rows
     The caption of an image will be a lorem-ipsum sentence
     """
     mod = random.choice([0, 1])
     scale_width = random.choice([0.5, 0.75, 1])
     scale_height = random.choice([0.5, 0.75, 1, 1.5, 2])
     with open('./lorem-ipsum-caption.txt', 'r', encoding='UTF-8') as f:
         all = f.readlines()
         caption_name = random.choice(all)
     for root, dirnames, filenames in os.walk('./img'):
         img = os.path.join(root + '/', random.choice(filenames))
     if mod == 0:
         with self.doc.create(Figure(position='htbp')) as fig:
             fig.add_image(img,
                           width=NoEscape(r'%f\linewidth' % scale_width))
             fig.add_caption(caption=caption_name)
     else:
         img_name = '{.' + img.split('.')[1] + '}.' + img.split('.')[2]
         with self.doc.create(MyFigure(options='hb')):
             self.doc.append(Command('centering'))
             self.doc.append(
                 Command(
                     'includegraphics',
                     options=Options(
                         NoEscape(
                             r'width=%f\textwidth, height=%f\textwidth' %
                             (scale_width, scale_height * 0.3))),
                     arguments=NoEscape(img_name)))
             self.doc.append(Command('caption', caption_name))
Exemplo n.º 5
0
 def _construct_title_page(self):
     authors = '\\\\ '.join([escape_latex(a) for a in self.authors()])
     return [
         Command('title', [self.title]),
         NoEscape('\\author{{ \\textbf{{Authors}} \\\\ {} }}'.format(authors)),
         Command('maketitle'),
     ]
Exemplo n.º 6
0
    def __init__(self):
        super().__init__()

        self.preamble.append(Command('title', 'Awesome Title'))
        self.preamble.append(Command('author', 'Anonymous author'))
        self.preamble.append(Command('date', NoEscape(r'\today')))
        self.append(NoEscape(r'\maketitle'))
Exemplo n.º 7
0
 def __setup_preamble(self) -> None:
     """
     Setup preamble of the LaTeX document.
     :return: None
     """
     preamble = self.doc.preamble
     issue = self.data[0]
     preamble.append(NoEscape(r"\UseRawInputEncoding"))
     preamble.append(Command("title", issue["issue_key"]))
     author = issue["author"] if issue["author"] else "no author"
     preamble.append(Command("author", author))
     preamble.append(Command("date", issue["created"].split("T")[0]))
     preamble.append(
         Command(
             "lstset",
             NoEscape("tabsize = 4,"
                      r"showstringspaces = false,"
                      r"numbers = left,"
                      r"commentstyle = \color{darkgreen} \ttfamily,"
                      r"keywordstyle = \color{blue} \ttfamily,"
                      r"stringstyle = \color{red} \ttfamily,"
                      r"rulecolor = \color{black} \ttfamily,"
                      r"basicstyle = \footnotesize \ttfamily,"
                      r"frame = single,"
                      r"breaklines = true,"
                      r"numberstyle = \tiny")))
     preamble.append(NoEscape(r"\definecolor{darkgreen}{rgb}{0,0.6,0}"))
Exemplo n.º 8
0
def add_header(doc, meal):
    doc.append(
        Command('renewcommand',
                arguments=Command('arraystretch'),
                extra_arguments='1.75'))
    doc.append(NoEscape(r'\definecolor{light-gray}{gray}{0.85}'))
    doc.append(Command('arrayrulecolor', arguments=NoEscape(r'light-gray')))

    with doc.create(Table()):
        with doc.create(Tabularx(
                "X r",
                width_argument=NoEscape(r'\textwidth'))) as table_content:
            # add header
            table_content.add_row([
                NoEscape(r'\LARGE \textbf{' + meal['meal_name'] + '}'),
                NoEscape(r'\color{gray} \large \textbf{' +
                         meal['meal_date'].strftime("%a, %d. %b") + '}')
            ])

            table_content.add_row([
                NoEscape(r'\small \textit{(' + meal['meal_weekview_name'] +
                         ')}'),
                NoEscape(r'\color{gray} \large \textbf{' +
                         meal['meal_used_as'] + '}')
            ])
            table_content.add_hline()
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)
Exemplo n.º 10
0
def generate_cover(doc):
		"""
		Generate a cover for generate_info_report func
		Cover contains name, date and branch info
		:param doc: a Document Class instance
		:return: null
		"""

		## Convert in default command of LaTeX to make title
		## \title{}
		## \author{}
		## \date{}
		doc.preamble.append(Command('title', 'RiMEA-Projekt Analyse'))
		doc.preamble.append(Command('author', get_git_status()[1]))
		doc.preamble.append(Command('date', get_git_status()[2]))

		## Use titling package to add line on title
		doc.packages.append(Package('titling'))

		branch = r"\begin{center}Branch: "+ get_git_status()[0] + "\par"
		doc.preamble.append(Command('predate', NoEscape(branch)))

		commit = r"\par commit: " + get_git_status()[3] + "\par\end{center}"
		doc.preamble.append(Command('postdate', NoEscape(commit)))

		doc.append(NoEscape(r'\maketitle'))
Exemplo n.º 11
0
    def __init__(self, fontclass):
        super().__init__()
        self.preamble.append(Command('usepackage', fontclass))
        self.preamble.append(NoEscape(r'\usepackage{float}'))

        # geometry_options = {
        #     "margin": "0.5in",
        #     "bottom": "0.6in",
        # }
        #
        # self.preamble.append(Command('geometry_options', "margin=0.5in"))

        self.preamble.append(
            NoEscape(
                r'\usepackage[margin = 0.5in, head = 1in, bottom = 1in]{geometry}'
            ))
        self.preamble.append(NoEscape(r'\usepackage[export]{adjustbox}'))

        # self.preamble.append(NoEscape(r'\usepackage{geometry}\geometry{a4paper,total={170mm,257mm},left=20mm,top=20mm}'))
        self.preamble.append(
            Command('title',
                    'Multilocus Sequence Typing Report for multiple isolates'))
        # self.preamble.append(Command('author', 'Anonymous author'))
        self.preamble.append(Command('date', NoEscape(r'\today')))
        self.append(NoEscape(r'\maketitle'))
Exemplo n.º 12
0
    def set_format1(self):
        """设置为常用格式,英文字体 Times,章节标题左对齐,大标题"""

        self.doc.preamble.append(Command('setmainfont', 'Times New Roman'))
        self.doc.preamble.append(
            Command('CTEXsetup', 'section',
                    NoEscape(r'format={\raggedright\bfseries\Large}')))
Exemplo n.º 13
0
 def rep_vm(self, doc, rep):
     doc.append(Command(NoEscape(r'begin{itemize}')))
     for s in rep:
         doc.append(Command(NoEscape(r'item[\square]')))
         doc.append(Command(NoEscape(r'hspace{2mm}')))
         doc.append(s[1])
     doc.append(Command(NoEscape(r'end{itemize}')))
Exemplo n.º 14
0
def createMultipleChoiceQuestion(doc, question, *answers):
    doc.append(NoEscape(r'\question ' + question))
    doc.append(Command('begin', 'checkboxes'))
    for x in answers:
        doc.append(Command('choice', x))
    doc.append(Command('end', 'checkboxes'))
    doc.append(Command('vspace', '1in'))
Exemplo n.º 15
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
Exemplo n.º 16
0
    def __init__(self):
        self.doc = pylatex.Document(args.experiment)

        self.doc.packages.append(Package("hyperref", options=["hidelinks"]))
        self.doc.packages.append(Package("etoc"))

        self.doc.preamble.append(Command("title", "DATA Leakage Report"))
        self.doc.preamble.append(Command("author", "Fraunhofer AISEC"))
        self.doc.preamble.append(Command("date", pylatex.NoEscape(r"\today")))

        self.doc.append(
            NoEscape(
                "\lstdefinestyle{stylecpp}{\n"
                "language=C++,\n" + Report.lstlisting_default_style
            )
        )
        self.doc.append(
            NoEscape(
                "\lstdefinestyle{styleasm}{\n"
                "language=[x86masm]Assembler,\n" + Report.lstlisting_default_style
            )
        )

        self.doc.append(NoEscape(r"\maketitle"))
        self.doc.append(NewPage())

        self.doc.append(NoEscape(r"\setcounter{tocdepth}{1}"))
        self.doc.append(NoEscape(r"\tableofcontents"))
        self.doc.append(NoEscape(r"\setcounter{tocdepth}{2}"))
        self.doc.append(NewPage())
Exemplo n.º 17
0
def generate_options(document: Document) -> Document:
    document.preamble.append(Command("raggedbottom"))
    document.preamble.append(Command("newlength"))
    document.preamble.append(Command("chunktoheight"))
    document.preamble.append(
        Command("setcounter", "secnumdepth", extra_arguments="0"))
    return document
Exemplo n.º 18
0
def create_cs170_hw(num="0", author="", questions=[]):
    # Create document
    doc = Document()

    #Inclue packages
    doc.packages.append(Package('amsmath'))
    doc.packages.append(Package('amssymb'))
    doc.packages.append(Package('enumitem'))

    # Make title
    title = 'CS 170 - HW %d' % (num)
    doc.preamble.append(Command('title', bold(title)))
    doc.preamble.append(Command('author', author))
    doc.preamble.append(Command('date', ''))
    doc.append(NoEscape(r'\maketitle'))

    # Instructions
    #with doc.create(Section("Instructions")) as section:
    #    section.append("N/A")

    # Create questions
    for question in questions:
        name = question[0]
        parts = question[1]
        with doc.create(Section(name)):
            if (parts > 0):
                with doc.create(
                        Enumerate(enumeration_symbol=r"(\alph*)")) as enum:
                    for _ in range(0, parts):
                        enum.add_item("")

    # Generate Latex file
    file_name = "cs170_hw" + str(num)
    doc.generate_tex(file_name)
    print("%s.tex generated!" % (file_name))
Exemplo n.º 19
0
    def _create_result_file(self, fname: str, width: str, title: str,
                            author: str, *args, **kwargs) -> None:
        """Create a experiment result file.

        :param fname:
        :param width:
        :param title:
        :param author:
        :param args:
        :param kwargs:
        :return:
        """
        geometry_options = {"right": "2cm", "left": "2cm"}
        doc = Document(fname, geometry_options=geometry_options)

        doc.preamble.append(Command('title', title))
        doc.preamble.append(Command('author', author))
        doc.preamble.append(Command('date', NoEscape(r'\today')))
        doc.append(NoEscape(r'\maketitle'))

        self._add_overview(doc)
        self._add_results(doc, width, *args, **kwargs)
        self._add_timing_report(doc)
        self._add_performance(doc)
        self._add_exp_params(doc)

        doc.generate_pdf(clean_tex=True)
Exemplo n.º 20
0
    def mealplan_to_latex(self) -> None:
        self._space()

        self.doc.preamble.append(Command("usepackage", "mealplan"))
        self._add_tex_title("Data")

        self._space()
        self.doc.append(Command("firstdate", self.mealplan.start_date))
        self.doc.append(Command("lastdate", self.mealplan.end_date))

        self._space()

        self._add_tex_title("Doc")
        self.doc.append(Command("mytitle"))

        self._space()

        for i, d in enumerate(self.mealplan.days):
            self.doc.append(NoEscape(f"%Day {i+1}"))
            self.doc.append(d.latex_command())
            self._space()

        self.doc.generate_pdf(clean_tex=False, clean=True)

        self._move_pdf()
Exemplo n.º 21
0
 def generate(self):
     '''
     main function that generate the report and call the
     functions of the report sections
     '''
     self.doc.packages.append(
         Package('geometry', options=['tmargin=1cm', 'lmargin=0.5cm']))
     # cover page #
     self.doc.preamble.append(Command(
         'title',
         'Experiemts Report',
     ))
     self.doc.preamble.append(Command('author', 'ATOM'))
     self.doc.append(NoEscape(r'\maketitle'))
     self.doc.append(NoEscape(r'\pagebreak'))
     # summary #
     self.gen_summary(self.experiments.iloc[0][1])
     self.doc.append(NoEscape(r'\pagebreak'))  #start new page
     # Top N Models #
     self.draw_top_models(4)
     self.doc.append(NoEscape(r'\pagebreak'))  #start new page
     # Graphs #
     visu = visualizer(save_dir=self.path)
     self.gen_graphs(visu)
     # generate pdf file #
     self.doc.generate_pdf('example')
     print 'Finished Report Generation'
 def addReferences(self, font, spacing, size, item_spacing):
     """
     This function can randomly insert a batch of references
     with randomly choiced font, size and line spacing
     """
     self.doc.append(UnsafeCommand('balance',
                                   packages=[Package('balance')]))
     item_spacing = str(spacing * float(item_spacing))
     item_spacing = item_spacing + 'ex'
     refs = self.getReferences(font)
     mode = random.choice([1, 2])
     with self.doc.create(SPACING(arguments=spacing)):
         self.doc.append(Command(size))
         if mode == 1:
             with self.doc.create(THEBIBLIOGRAPHY(arguments='99')):
                 self.doc.append(
                     UnsafeCommand('addtolength',
                                   '\itemsep',
                                   extra_arguments=item_spacing))
                 for ref in refs:
                     ref = '\\bibitem{ref}' + ref
                     self.doc.append(ref)
         else:
             i = 0
             with self.doc.create(Section('References', numbering=False)):
                 for ref in refs:
                     i += 1
                     ref = '{[}' + str(i) + '{]}' + ref
                     self.doc.append(NoEscape(ref))
     self.doc.append(Command('clearpage'))
Exemplo n.º 23
0
 def addExtracurriculars(self, activities):
     self.doc.append(
         Command("begin", ["rSection", "Extracurricular Activities"]))
     self.doc.append(Command("FirstDatedEntry", activities[0]))
     for act in activities[1:]:
         self.doc.append(Command("DatedEntry", act))
     self.doc.append(Command("end", "rSection"))
Exemplo n.º 24
0
def set_up(doc):
    """Add packages, set preliminary settings for this doc."""
    # Add packages
    doc.preamble.append(Package('hyperref'))
    doc.preamble.append(Package('titlesec'))

    # Hide "Chapter 1" etc. (just show chapter name)
    doc.preamble.append(NoEscape(r'\titleformat{\chapter}[display]'))
    doc.preamble.append(NoEscape(r'{\normalfont\bfseries}{}{0pt}{\Huge}'))

    # Ignore page numbers until we get to the actual body
    doc.append(NoEscape(r'\pagenumbering{gobble}'))

    # Title Info
    doc.preamble.append(Command('title', 'Maia\'s Songbook'))
    doc.preamble.append(Command('author', 'Maia McCormick'))
    doc.preamble.append(Command('date', NoEscape(r'\today')))
    doc.append(NoEscape(r'\maketitle'))

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

    # Okay, show page numbers again
    doc.append(NoEscape(r'\pagenumbering{arabic}'))

    return doc
Exemplo n.º 25
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)
Exemplo n.º 26
0
 def _write_title(self) -> None:
     """Write the title content of the file. Override if you want to build on top of base traceability report.
     """
     self.doc.preamble.append(Command('title', self.system.summary.name))
     self.doc.preamble.append(Command('author', f"FastEstimator {fe.__version__}"))
     self.doc.preamble.append(Command('date', NoEscape(r'\today')))
     self.doc.append(NoEscape(r'\maketitle'))
Exemplo n.º 27
0
 def rep_libre(self, doc, l):
     i = 0
     while (i < l):
         doc.append(Command("par"))
         doc.append(Command(NoEscape(r'dotfill')))
         i += 1
     doc.append("\n")
Exemplo n.º 28
0
    def _report_attack_results(self):
        """
        Create subsubsection describing the most important results of the attack.

        This subsection contains results only for the first target model.
        """
        tm = 0  # Specify target model
        self.report_section.append(Subsubsection("Attack Results"))
        res = self.attack_results

        with self.report_section.create(MiniPage(width=r"0.49\textwidth")):
            self.report_section.append(Command("centering"))
            with self.report_section.create(Tabular("|l|c|")) as result_tab:
                result_tab.add_hline()
                result_tab.add_row(["True Positives", round(res["tp"][tm], 3)])
                result_tab.add_hline()
                result_tab.add_row(["True Negatives", round(res["tn"][tm], 3)])
                result_tab.add_hline()
                result_tab.add_row(["False Positives", round(res["fp"][tm], 3)])
                result_tab.add_hline()
                result_tab.add_row(["False Negatives", round(res["fn"][tm], 3)])
                result_tab.add_hline()
                result_tab.add_row(["Accuracy", round(res["accuracy"][tm], 3)])
                result_tab.add_hline()
                result_tab.add_row(["Precision", round(res["precision"][tm], 3)])
                result_tab.add_hline()
                result_tab.add_row(["Recall", round(res["recall"][tm], 3)])
                result_tab.add_hline()

            self.report_section.append(Command("captionsetup", "labelformat=empty"))
            self.report_section.append(
                Command("captionof", "table", extra_arguments="Attack Summary")
            )
Exemplo n.º 29
0
def build_document(transcript):
    """
    Processes a Transcript object to build a LaTeX document.
    """
    # Open temporary file
    doc = Document(documentclass='scrartcl',
                   title=transcript.title,
                   subtitle=transcript.school,
                   author=transcript.student,
                   date=transcript.date.strftime('%d %B %Y'),
                   temporary=True)

    doc.packages.append(Package('geometry', option='margin=1.0in'))
    doc.preamble.append(
        Command('renewcommand', argument=['\\familydefault', '\\sfdefault']))

    doc.append(Command('maketitle'))

    # Iterate through each transcript section
    for t_section in transcript.sections:
        # Create new section
        s = Section(escape_latex(t_section.title))
        # Add content to section
        for s_line in t_section.content:
            s_line = '\t'.join(s_line)
            s.append(escape_latex(s_line) + ' \\\n')

        # Add subsections to section
        for t_subsection in t_section.subsections:
            ss = Subsection(escape_latex(t_subsection.title))
            num_cols = max(len(l) for l in t_subsection.content)
            ss_table = Table(' l ' * num_cols)
            # Add content to subsection
            for ss_line in t_subsection.content:

                ss_line = '\t'.join(ss_line)
                if ss_line.startswith('Course Topic'):
                    ss_table.append('&')
                    ss_table.add_multicolumn(num_cols - 1, 'l',
                                             escape_latex(ss_line))
                    ss_table.append(r'\\')
                elif not ss_line[:3].isupper() and not ss_line.startswith(
                        'Test'):
                    ss_table.add_multicolumn(num_cols, 'l',
                                             escape_latex(ss_line))
                    ss_table.append(r'\\')
                else:
                    if ss_line.startswith('TERM'):
                        ss_table.add_hline()
                    filled = escape_latex(ss_line).split('\t')
                    filled += (num_cols - len(filled)) * ['']
                    ss_table.add_row(filled)

            ss.append(ss_table)
            s.append(ss)

        doc.append(s)
    doc.generate_pdf(clean=True)

    return doc
Exemplo n.º 30
0
def issth(bookNumber, chapterStart, chapterMax, bookTitle):
    novelTitle = "I Shall Seal The Heavens"
    author = "Er Gen"
    baseURL = "http://www.wuxiaworld.com/issth-index/issth-book-%d-chapter-%d"

    B = bookNumber
    C = chapterMax
    # C = 23

    doc = Document(documentclass='scrartcl', document_options='titlepage')
    doc.packages.append(Package('ragged2e'))
    doc.packages.append(Package('geometry', options='margin=1in'))
    # doc = Document(document_options='titlepage')

    for c in range(chapterStart, C + 1):
        url = baseURL % (B, c)
        print 'Parsing', url

        page = requests.get(url)
        tree = html.fromstring(page.content)

        title = tree.xpath('//div[@itemprop="articleBody"]/p/strong')
        if not title:
            title = tree.xpath('//div[@itemprop="articleBody"]/strong')
        if not title:
            continue
        Chapter = unidecode(title[0].text_content())
        Book = bookTitle
        # for tit in title:

        # Chapter = title2.split(' - ')
        # Chapter = Chapter[1]

        if c == chapterStart:  # On first chapter, create title page
            # doc.preamble.append(Command('title',LargeText(bold(Book)) + NewLine() + MediumText('Book %d: %s' % (B, Book))))
            # doc.preamble.append(Command('title',Book + NoEscape('\\') + '\\large Book %d: %s' % (B, Book)))
            doc.preamble.append(Command('title', novelTitle))
            doc.preamble.append(Command('subtitle', 'Book %d: %s' % (B, Book)))
            doc.preamble.append(Command('author', author))
            doc.preamble.append(Command('date', ''))
            doc.append(NoEscape(r'\maketitle'))
        else:
            doc.append(NewPage())

        with doc.create(Section(Chapter, numbering=False)):
            addMainTextV2(doc, tree)

        time.sleep(5)

    try:
        doc.generate_pdf('%s - Book %d - %s' % (novelTitle, B, Book),
                         clean_tex=False,
                         compiler='pdflatex')
    except:
        val = raw_input('Failed to generate PDF...try again? (y/n): ')
        if val == 'y':
            doc.generate_pdf('%s - Book %d - %s' % (novelTitle, B, Book),
                             clean_tex=False,
                             compiler='pdflatex')