示例#1
14
def test_document():
    geometry_options = {
        "includeheadfoot": True,
        "headheight": "12pt",
        "headsep": "10pt",
        "landscape": True
    }

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

    repr(doc)

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

    doc.generate_tex(filepath='')
    doc.generate_pdf(filepath='', clean=True)
def basic_table():
    geometry_options = {"margin": "2.54cm", "includeheadfoot": True}
    doc = Document(page_numbers=True, geometry_options=geometry_options)

    batch_size_list = [8, 12, 16, 32]
    learning_rate_list = [1e-5, 2e-5, 5e-5, 1e-4]
    epochs_list = [2, 4, 8, 12]

    rows = []
    for batch_size in batch_size_list:
        for learning_rate in learning_rate_list:
            for epochs in epochs_list:
                row = []
                row.append(batch_size)
                row.append(learning_rate)
                row.append(epochs)
                row.append(0)
                rows.append(row)

    # Generate data table
    with doc.create(LongTable("l l l l")) as data_table:
        data_table.add_hline()
        data_table.add_row(["batch size", "learning rate", "epochs", "F1"])
        data_table.add_hline()
        data_table.end_table_header()
        data_table.add_hline()
        for i in range(len(rows)):
            data_table.add_row(rows[i])

    doc.generate_pdf("hyper_tune_bert", clean_tex=False)
示例#3
0
文件: test1.py 项目: jyxe/code_file
def genenerate_longtabu():
    geometry_options = {
        "margin": "2.54cm",
        "includeheadfoot": True
    }
    doc = Document(page_numbers=True, geometry_options=geometry_options)

    # Generate data table
    with doc.create(LongTable("l l l")) as data_table:
            data_table.add_hline()
            data_table.add_row(["header 1", "header 2", "header 3"])
            data_table.add_hline()
            data_table.end_table_header()
            data_table.add_hline()
            data_table.add_row((MultiColumn(3, align='r',
                                data='Containued on Next Page'),))
            data_table.add_hline()
            data_table.end_table_footer()
            data_table.add_hline()
            data_table.add_row((MultiColumn(3, align='r',
                                data='Not Containued on Next Page'),))
            data_table.add_hline()
            data_table.end_table_last_footer()
            row = ["Content1", "9", "Longer String"]
            for i in range(150):
                data_table.add_row(row)

    doc.generate_pdf("longtable", clean_tex=False)
示例#4
0
文件: parit.py 项目: ArthurG/parit
    def write(self):
        opening = self.config['opening'].replace(
            '$organization', self.posting.get('organization'))
        closing = self.config['closing'].replace(
            '$organization', self.posting.get('organization'))
        output = Document(documentclass='letter')
        output.preamble.append(Command('signature', self.config['sender']))
        output.preamble.append(
            Command('address', NoEscape(self.return_address())))
        output.preamble.append(Command('date', NoEscape(r'\today')))
        output.append(Command('begin', ['letter', self.employer_address()]))
        output.append(Command('opening', 'Dear Hiring Manager,'))
        output.append(opening + self.write_body())
        output.append(NewLine())
        output.append(NewLine())
        output.append(closing)
        output.append(Command('closing', 'Sincerely,'))
        output.append(Command('end', 'letter'))

        filename = '{0}_{1}'.format(
            self.posting['organization'],
            ' '.join(process_input(self.posting['job_title']))).replace(
                ' ', '_').lower()
        output.generate_pdf(filename)
        output.generate_tex(filename)
示例#5
0
def test():
    doc = Document("utils_escape_latex")
    section = Section('Escape LaTeX characters test')

    text = escape_latex('''\
    & (ampersand)
    % (percent)
    $ (dollar)
    # (number)
    _ (underscore)
    { (left curly brace)
    } (right curly brace)
    ~ (tilde)
    ^ (caret)
    \\ (backslash)
    --- (three minuses)
    a\xA0a (non breaking space)
    [ (left bracket)
    ] (right bracket)
    ''')

    section.append(text)
    doc.append(section)

    doc.generate_pdf()
示例#6
0
def generate_info_report():
			"""
			Generate a report with cover, status und last 2 lines in log for every test
			"""

			## Define the geometry for LaTeX files
			geometry_options = {
					"head": "40pt",
					"margin": "0.5in",
					"bottom": "0.6in",
					"includeheadfoot": True
				}


			## Create the LaTeX object, a instance of Document Class
			doc = Document(documentclass='article', geometry_options=geometry_options)

			## Add cover
			generate_cover2(doc)
			doc.append(NewPage())

			## Add status table
			generate_status_tabel(doc)
			doc.append(NewPage())

			## Add last 2 lines in log.txt
			for i in range(1, 4):
					generate_info_list(doc, i)


			doc.generate_pdf("RiMEA-Projekt Analyse", clean_tex=False)
示例#7
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
示例#8
0
def generateTexTable(fname, colTitles, rowNames, rowDataList):

    # make sure all rows have same length
    max_data_length = max([len(rowdata) for rowdata in rowDataList])
    print("max data length: ", max_data_length)
    for rowdata in rowDataList:
        while len(rowdata) < max_data_length:
            rowdata += ['/']

    print colTitles
    colBaseTitle = colTitles[-1]
    colTitles = [colTitles[0]]
    j = 0
    while len(colTitles) < max_data_length + 1:
        colTitles.append(str(2**j) + " Layers " + colBaseTitle)
        j += 1

    geometry_options = {"tmargin": "1cm"}  #, "lmargin": "1cm"}
    doc = Document(geometry_options=geometry_options)

    with doc.create(Subsection('Table of something')):
        layout = ['|l'] * len(colTitles) + ['|']
        layout = ''.join(layout)
        print(layout)
        with doc.create(Tabular(layout)) as table:
            table.add_hline()
            table.add_row((colTitles))
            table.add_hline()
            for rowName, rowData in zip(rowNames, rowDataList):
                rowList = [rowName] + rowData
                print rowList
                table.add_row(tuple(rowList))
                table.add_hline(1, 1)
            table.add_hline()
    doc.generate_pdf(storeDir + fname, clean_tex=False)
示例#9
0
文件: args.py 项目: cmrfrd/PyLaTeX
def test_document():
    geometry_options = {
        "includeheadfoot": True,
        "headheight": "12pt",
        "headsep": "10pt",
        "landscape": True
    }

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

    repr(doc)

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

    doc.generate_tex(filepath='')
    doc.generate_pdf(filepath='', clean=True)
示例#10
0
def main():
    geometry_options = {
        "margin": "0in",
        "headheight": "0pt",
        "headsep": "0pt",
        "voffset": "0mm",  # no change
        "hoffset": "1mm",
        "includeheadfoot": False,
        "paperheight": "5mm",
        "textheight": "5mm",
        "textwidth": "5mm",
        "paperwidth": "7mm",
        "marginparwidth": "0mm"
    }
    for char_combo in char_combos():
        doc = Document(
            geometry_options=geometry_options,
            documentclass="article",
            # document_options="convert",
            indent=False)
        doc.append(char_combo)
        file_path = "./pdf/" + char_combo.replace("\\", "").replace(
            "{", "").replace("}", "")
        doc.generate_pdf(file_path,
                         compiler="lualatex",
                         compiler_args=["-shell-escape"])
示例#11
0
def create_pdf_document(rows):
    geometry_options = {
        "head": "30pt",
        "bottom": "0.5in",
        "margin": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    with doc.create(LongTabu("X[l] X[2l] X[r] X[r]",
                             row_height=1.5)) as my_table:
        my_table.add_row(["Full name", "Email", "Contact", "Address"], \
             mapper=bold, color="pink"
            )
        my_table.add_empty_row()
        my_table.add_hline()

        for index, row in enumerate(rows):
            data_list = [row[1], row[2], row[3], row[4]]

            if (index % 2 == 0):
                my_table.add_row(data_list, color="gray")
            else:
                my_table.add_row(data_list, color="lightgray")

    doc.generate_pdf("users-details", clean_tex=False)
示例#12
0
def arxiv_search(search_query):

    url = 'http://export.arxiv.org/api/query?search_query=all:' + \
        search_query + '&start=0&max_results=5'
    data = urllib.request.urlopen(url).read()

    soup = bs(data, features='xml')
    title_array = []
    summary_array = []

    for i in soup.findAll('title'):
        title_array.append(i)

    for i in soup.findAll('summary'):
        summary_array.append(i)

    doc = Document()
    doc.packages.append(
        Package(
            'geometry',
            options=[
                'tmargin=1cm',
                'lmargin=1cm',
                'rmargin=1cm']))

    with doc.create(Section('Search results for \"' + search_query + '\"')):

        for i in range(1, 5):
            doc.append(Subsection(italic(title_array[i].string)))
            doc.append(summary_array[i].string)

    doc.generate_pdf()
示例#13
0
class Txt2Pdf:
    def __init__(self, version=None):
        self.doc = Document('basic')
        self.doc.preamble.append(Command('title', 'Vega Evaluation'))
        self.doc.preamble.append(Command('author', 'vega {}'.format(version)))
        self.doc.preamble.append(Command('date', NoEscape(r'\today')))
        self.doc.append(NoEscape(r'\maketitle'))

    def table(self, csvFile=None, cType=None, pType=None):
        with self.doc.create(Section(cType)):
            self.doc.append('{} evaluation'.format(cType))
            with self.doc.create(Subsection('Accuracy')):

                with self.doc.create(LongTabu('|c|c|c|c|c|')) as table:
                    table.add_hline()
                    table.add_row(("eval", "type", "Precision", "Recall", "F1 Score"))
                    table.add_hline()

                    with open(csvFile) as f:
                        f_csv = csv.reader(f)
                        for row in f_csv:
                            e, t, p, r, f1 = row
                            table.add_row((e,t, p, r, f1))
                            table.add_hline()
    def pdf(self, pName):
        self.doc.generate_pdf(pName, clean_tex=False)
示例#14
0
def genenerate_table_rates(table_rates):
    doc = Document('basic', indent=True, page_numbers=False)

    steps = sorted(list(set([t["qty_dx"] for t in table_rates])))
    print(steps)
    basises = sorted(list(set([t["qty_bas"] for t in table_rates])))
    rates_L1 = {}
    rates_L2 = {}
    for t in table_rates:
        rates_L1[str(t["qty_dx"]) + "-" + str(t["qty_bas"])] = t["L1"]
        rates_L2[str(t["qty_dx"]) + "-" + str(t["qty_bas"])] = t["L2"]
    print(rates_L1)
    format_header = "".join(["|c|" for i in range(len(steps))])
    # Generate data table
    with doc.create(Tabular(format_header)) as table:
        table.add_hline()
        table.add_row(steps)
        table.add_hline()
        for basis in basises:
            row = []
            for step in steps:
                if (str(step) + "-" + str(basis) in rates_L1):
                    row.append(rates_L1[str(step) + "-" + str(basis)])
                else:
                    row.append('')
            table.add_row(row)

    print(table)
    doc.generate_pdf("rates", clean_tex=False)
    pages = convert_from_path('rates.pdf', 500)
    for page in pages:
        page.save('out.jpg', 'JPEG')
示例#15
0
class Txt2Pdf:
    def __init__(self, version=None):
        self.doc = Document('basic')
        self.doc.preamble.append(Command('title', 'Vega Evaluation'))
        self.doc.preamble.append(Command('author', 'vega {}'.format(version)))
        self.doc.preamble.append(Command('date', NoEscape(r'\today')))
        self.doc.append(NoEscape(r'\maketitle'))

    def table(self, csvFile=None, cType=None, pType=None, level=None):
        with self.doc.create(Section(cType)):
            self.doc.append('{} evaluation'.format(cType))
            with self.doc.create(Subsection('Qps/Mem detail')):

                with self.doc.create(LongTabu('|c|c|c|')) as table:
                    table.add_hline()
                    table.add_row(("Model", "Qps", "Mem"))
                    table.add_hline()

                    with open(csvFile) as f:
                        f_csv = csv.reader(f)
                        for row in f_csv:
                            m, q, e = row
                            if level == 2:
                                e = '-'
                            table.add_row((m, q, e))
                            table.add_hline()

    def pdf(self, pName):
        self.doc.generate_pdf(pName, clean_tex=False)
示例#16
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
def render(img_filepath, output_list):
    image_filename = img_filepath.split('/')[-1]
    cwd = os.getcwd() + '/' + output_list[2]
    shutil.copy2(img_filepath, cwd)

    #print(image_filename)

    geometry_options = {"tmargin": "1cm", "lmargin": "1cm"}
    doc = Document(geometry_options=geometry_options)
    #creates image section in LaTeX

    with doc.create(Section("Xcos")):
        with doc.create(Figure(position='h!')) as abs_pic:
            abs_pic.add_image(image_filename, width='450px')
            doc.append("\n\n\n")
    #creates Context section in LaTeX if context exists
    if output_list[1]:
        with doc.create(Subsection("Context")):
            with doc.create(Itemize()) as itemize:
                for data in output_list[1]:
                    itemize.add_item(data)
    #creates Block section in LaTeX
    with doc.create(Subsection("Blocks")):
        for i in output_list[0]:
            if i is not None:
                doc.append("\n\n\n")
                with doc.create(Tabular('|c|c|')) as table:
                    table.add_hline()
                    for key, value in i.parameters().items():
                        table.add_row(key, value)
                        table.add_hline()

    file_path = output_list[2] + '/' + output_list[2]
    doc.generate_pdf(file_path, clean_tex=False)
示例#18
0
def generate_exam(book):
    '''
    this is used to generate in exam style.
    Suitable for Math
    '''
    print 'generating book: {title}'.format(title=book['title'])
    doc = Document(documentclass='exam')
    doc = _setup_doc(doc, book)

    for section in book['sections']:
        with doc.create(Section(section['title'], numbering=False)):
            with doc.create(Questions()) as questions:
                for exercise in section['exercises']:
                    if isinstance(exercise, basestring):
                        questions.add_question(NoEscape(exercise))
                    else:
                        questions.add_question(
                            NoEscape(exercise['description']))
                        with questions.create(Parts()) as parts:
                            for sub_exercise in exercise['exercises']:
                                parts.add_part(NoEscape(sub_exercise))

    book_name = '{target_path}/{user} {title}'.format(target_path=TARGET_PATH,
                                                      user=book['user'],
                                                      title=book['title'])
    # import pdb; pdb.set_trace()
    doc.generate_pdf(book_name, clean_tex=False, compiler='xelatex')
    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)
示例#20
0
def circuit_to_pdf_using_qcircuit_via_tex(circuit: circuits.Circuit,
                                          filepath: str,
                                          pdf_kwargs=None,
                                          qcircuit_kwargs=None,
                                          clean_ext=('dvi', 'ps'),
                                          documentclass='article'):
    """Compiles the QCircuit-based latex diagram of the given circuit.

    Args:
        circuit: The circuit to produce a pdf of.
        filepath: Where to output the pdf.
        pdf_kwargs: The arguments to pass to generate_pdf.
        qcircuit_kwargs: The arguments to pass to
            circuit_to_latex_using_qcircuit.
        clean_ext: The file extensions to clean up after compilation. By
            default, latexmk is used with the '-pdfps' flag, which produces
            intermediary dvi and ps files.
        documentclass: The documentclass of the latex file.
    """
    pdf_kwargs = {'compiler': 'latexmk', 'compiler_args': ['-pdfps'],
                  **({} if pdf_kwargs is None else pdf_kwargs)}
    qcircuit_kwargs = {} if qcircuit_kwargs is None else qcircuit_kwargs
    tex = circuit_to_latex_using_qcircuit(circuit, **qcircuit_kwargs)
    doc = Document(documentclass=documentclass, document_options='dvips')
    doc.packages.append(Package('amsmath'))
    doc.packages.append(Package('qcircuit'))
    doc.append(NoEscape(tex))
    doc.generate_pdf(filepath, **pdf_kwargs)
    for ext in clean_ext:
        try:
            os.remove(filepath + '.' + ext)
        except (OSError, IOError) as e:
            if e.errno != errno.ENOENT:
                raise
class pdf_generator:

    def __init__(self, manager, results):
        self.mng = manager
        self.res = results

    def setup_pdf(self, language):
        self.doc = Document(document_options="a4paper,12pt", documentclass="article")
        self.doc.preamble.append(NoEscape(header.PDFsettings))

        self.language = language

        self.pdf = add_to_pdf(self.doc)

        self.tpdf = translate_PDF_Mohr(self.language)

    def generate_pdf_plain_state(self, language, pdf_path, filename):
        self.setup_pdf(language)

        append_plain_state(self, self.mng, self.res).append_all()

        self.doc.generate_pdf(fr'{pdf_path}\{filename}',
                              compiler='pdflatex',
                              win_no_console=True,
                              compiler_args=["-enable-installer"])

    def generate_pdf_triple_state(self, language, pdf_path, filename):
        self.setup_pdf(language)

        append_triple_state(self, self.mng, self.res).append_all()

        self.doc.generate_pdf(fr'{pdf_path}\{filename}',
                              compiler='pdflatex',
                              win_no_console=True,
                              compiler_args=["-enable-installer"])
示例#22
0
def generate_table(book):
    '''
    this is used to generate in table style.
    suitable for language learning: e.g. Spanish / English etc
    '''
    print 'generating book: {title}'.format(title=book['title'])
    doc = Document(geometry_options=GEOMETRY_OPTIONS)
    doc = _setup_doc(doc, book)
    # doc.append(NoEscape(r'\maketitle'))

    section_count = 0
    for section in book['sections']:
        with doc.create(Section(section['title'], numbering=False)):
            with doc.create(LongTabu(_TABLE_FORMAT, row_height=1.5)) as table:
                table.end_table_header()
                row_elements = []
                for exercise in section['exercises']:
                    row_elements.append(NoEscape(exercise[0]))
                    row_elements.append(NoEscape(exercise[1]))
                    if len(row_elements) == 6:
                        table.add_row(row_elements)
                        row_elements = []
                    # table.add_hline()
        section_count += 1
        if section_count % 2 == 0:
            doc.append(NewPage())

    book_name = '{target_path}/{user} {title}'.format(target_path=TARGET_PATH,
                                                      user=book['user'],
                                                      title=book['title'])
    doc.generate_pdf(book_name, clean_tex=True, compiler='xelatex')
示例#23
0
def circuit_to_pdf_using_qcircuit_via_tex(circuit: circuits.Circuit,
                                          filepath: str,
                                          pdf_kwargs=None,
                                          qcircuit_kwargs=None,
                                          clean_ext=('dvi', 'ps'),
                                          documentclass='article'):
    """Compiles the QCircuit-based latex diagram of the given circuit.

    Args:
        circuit: The circuit to produce a pdf of.
        filepath: Where to output the pdf.
        pdf_kwargs: The arguments to pass to generate_pdf.
        qcircuit_kwargs: The arguments to pass to
            circuit_to_latex_using_qcircuit.
        clean_ext: The file extensions to clean up after compilation. By
            default, latexmk is used with the '-pdfps' flag, which produces
            intermediary dvi and ps files.
        documentclass: The documentclass of the latex file.
    """
    pdf_kwargs = {'compiler': 'latexmk', 'compiler_args': ['-pdfps'],
                  **({} if pdf_kwargs is None else pdf_kwargs)}
    tex = circuit_to_latex_using_qcircuit(circuit, **qcircuit_kwargs)
    doc = Document(documentclass=documentclass, document_options='dvips')
    doc.packages.append(Package('amsmath'))
    doc.packages.append(Package('qcircuit'))
    doc.append(NoEscape(tex))
    doc.generate_pdf(filepath, **pdf_kwargs)
    for ext in clean_ext:
        try:
            os.remove(filepath + '.' + ext)
        except (OSError, IOError) as e:
            if e.errno != errno.ENOENT:
                raise
示例#24
0
def create_latex_specification(i_feature_list,
                               i_section_column,
                               i_sub_section_column=None,
                               i_sub_sub_section_column=None,
                               i_description_column=None,
                               i_characteristic_columns=None,
                               i_ranking_columns=None,
                               i_title='Specification',
                               i_authors='Author NAMES',
                               i_file_name='specification'):
    a_ranking_columns = i_ranking_columns if i_ranking_columns is not None else [
        i_section_column, i_sub_section_column
    ]
    geometry_options = {}
    a_doc = Document(geometry_options=geometry_options)
    add_first_page(a_doc, i_title, i_authors)
    a_doc.append(NoEscape(r'\tableofcontents'))
    a_doc.append(NewPage())
    i_feature_list.sort_values(by=a_ranking_columns, inplace=True)
    a_sections_dict = defaultdict(lambda: defaultdict(list))
    a_characteristic_bloc = CurrentCharacteristicBloc()
    for it_feature_row in i_feature_list.itertuples():
        a_specification_line = SpecificationLine(
            i_section_column, i_sub_section_column, i_sub_sub_section_column,
            i_description_column, i_characteristic_columns, it_feature_row)
        create_section(a_doc, a_specification_line, a_sections_dict,
                       a_characteristic_bloc)
    a_doc.generate_pdf(i_file_name, clean_tex=False)
示例#25
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)
示例#26
0
def start():
    info = get_json(f"../{defaults.get('jsonOutput')}")

    doc = Document(default_filepath=defaults.get('pdfPath'))

    for artist, artistListStuff in info.items():
        with doc.create(Section(f'Artist: {artist}')):
            importLinedFigures(doc, artistListStuff['base_objects'])
        for subsection, subsectionList in artistListStuff['sub_objects'].items(
        ):
            with doc.create(Subsection(f'Folder: {subsection}')):
                importLinedFigures(doc, subsectionList)
            doc.append(NoEscape(r'\clearpage'))
        for subsubsection, subsubsectionList in artistListStuff[
                'sub_sub_objects'].items():
            with doc.create(Subsubsection(f'Sub Folder: {subsubsection}')):
                importLinedFigures(doc, subsubsectionList)
        doc.append(NoEscape(r'\clearpage'))
    try:
        doc.generate_tex()
        doc.generate_pdf(clean_tex=False)
        print('done?')
    except Exception as e:
        print(f"OH NO")
        print(e)
示例#27
0
def test():
    doc = Document("utils_escape_latex")
    section = Section('Escape LaTeX characters test')

    text = escape_latex('''\
    & (ampersand)
    % (percent)
    $ (dollar)
    # (number)
    _ (underscore)
    { (left curly brace)
    } (right curly brace)
    ~ (tilde)
    ^ (caret)
    \\ (backslash)
    --- (three minuses)
    a\xA0a (non breaking space)
    [ (left bracket)
    ] (right bracket)
    ''')

    section.append(text)
    doc.append(section)

    doc.generate_pdf()
示例#28
0
def test():
    doc = Document("multirow_cm")

    with doc.create(Section('Multirow Test')):
        with doc.create(Subsection('Multicol')):
            # we need to keep track of the object here
            with doc.create(Tabular('|c|c|')) as table1:
                table1.add_hline()
                table1.add_multicolumn(2, '|c|', 'Multicol')
                table1.add_hline()
                table1.add_row((1, 2))
                table1.add_hline()
                table1.add_row((3, 4))
                table1.add_hline()

        with doc.create(Subsection('Multirow')):
            with doc.create(Tabular('|c|c|c|')) as table2:
                table2.add_hline()
                table2.add_multirow(3, '*', 'Multirow', cells=((1, 2), (3, 4),
                                                               (5, 6)))
                table2.add_hline()
                table2.add_multirow(3, '*', 'Multirow2')
                table2.add_hline()

    doc.generate_pdf()
示例#29
0
    def generateLatex(self):

        geometry_options = {"tmargin": "1cm",
                            "lmargin": "3cm", "bmargin": "2cm"}
        doc = Document(geometry_options=geometry_options)

        doc.packages.append(Package("float"))

        for chapter in self.chapters:
            with doc.create(Section(str(chapter.name))):
                # Chapter Intro
                if not chapter.introLines == []:
                    for line in chapter.introLines:
                        if line.lineType == "normal":
                            doc.append(line.content)
                # Subchapter
                for subChapter in chapter.subChapters:
                    with doc.create(Subsection(subChapter.name)):
                        if not subChapter.lines == []:
                            for line in subChapter.lines:
                                doc = self.createParagraph(
                                    doc, line)
                        if not subChapter.sschapters == []:
                            for sschapter in subChapter.sschapters:
                                with doc.create(Subsubsection(sschapter.name)):
                                    if not sschapter.lines == []:
                                        for line in sschapter.lines:
                                            doc = self.createParagraph(
                                                doc, line)

        doc.generate_pdf(self.filePath+self.filename, clean_tex=False)
示例#30
0
    def handle_request(self, latex_expr):
        """Uploads LaTeX formated equations to imgur and returns a URL.

        Args:
            latex_expr: string that is to converte to LaTeX, requires that string is enclosed by $.
            >>> handle_request("$\int \sqrt{1+\cos x + \sin x} dx$")
        Returns:
            A tuple (str, (int, int)), where str is the url, on imgur and
            the tuples are the dimensions of the image (width, height).
        """
        # create a bare bones latex document with only the one line specified from the user in the document.
        doc = Document(documentclass='minimal')
        doc.packages = [Package(NoEscape(i)) for i in self.packages.split(',')]
        doc.append(NoEscape(latex_expr))
        doc.generate_pdf('default',
                         compiler_args=[
                             '-no-shell-escape',
                         ],
                         compiler="pdflatex",
                         clean=True,
                         clean_tex=True)
        # These are normal Linux commands that are used to convert the pdf
        # file created by pylatex into a snippet
        os.system("pdfcrop default.pdf")
        os.system("pdftoppm default-crop.pdf|pnmtopng > default.png")
        path = os.path.abspath('default.png')
        uploaded_image = self._client.upload_image(path, title="LaTeX")
        return uploaded_image.link, OnlineImage.get_local_image_info(path)
示例#31
0
def genenerate_longtabu():
    geometry_options = {
        "landscape": True,
        "margin": "0.5in",
        "headheight": "20pt",
        "headsep": "10pt",
        "includeheadfoot": True
    }
    doc = Document(page_numbers=True, geometry_options=geometry_options)

    # Generate data table
    with doc.create(LongTabu("X[r] X[r] X[r] X[r] X[r] X[r]")) as data_table:
        header_row1 = ["Prov", "Num", "CurBal", "IntPay", "Total", "IntR"]
        data_table.add_row(header_row1, mapper=[bold])
        data_table.add_hline()
        data_table.add_empty_row()
        data_table.end_table_header()
        data_table.add_row(
            ["Prov", "Num", "CurBal", "IntPay", "Total", "IntR"])
        row = [
            "PDADASDASDSADSADSADASDASDSADASDASA", "9", "$100", "%10", "$1000",
            "Test"
        ]
        for i in range(50):
            data_table.add_row(row)

    doc.append(bold("Grand Total:"))
    doc.append(HFill())
    doc.append(bold("Total"))

    doc.generate_pdf("longtabu", clean_tex=False)
示例#32
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
示例#33
0
def produce_table():
    # create document structure
    doc = Document("testtable")
    section = Section('Produce accessories table')
    test1 = Subsection('Test accessories table production')

    # test input code
    bench = [('Incline BP (4 x 12)'), ('Pull up (4 x Max)')]

    # test code
    accesory = bench
    table = Tabular('|c|c|c|c|c|c|c|c|c|')
    table.add_hline()
    table.add_row((MultiColumn(9, align='|c|', data='Accessories'), ))
    table.add_hline()
    table.add_row(('Exercise', 'Weight', 'Reps', 'Weight', 'Reps', 'Weight',
                   'Reps', 'Weight', 'Reps'))
    table.add_hline()
    for i in range(len(accesory)):
        table.add_row((str(accesory[i]), '', '', '', '', '', '', '', ''))
        table.add_hline()

    # append table to document
    test1.append(table)
    section.append(test1)
    doc.append(section)
    doc.generate_pdf(clean_tex=True)
示例#34
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')
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
示例#36
0
文件: pictures.py 项目: votti/PyLaTeX
def test():
    doc = Document()
    section = Section('Multirow Test')
    figure = Figure()
    image_filename = os.path.join(os.path.dirname(__file__),
                                  '../examples/kitten.jpg')
    figure.add_image(image_filename)
    figure.add_caption('Whoooo an imagage of a pdf')
    section.append(figure)
    doc.append(section)

    doc.generate_pdf()
示例#37
0
    def _upload_problem(self, problem):
        """Uploads a specified problem to imgur.

        Returns:
            A tuple (str, (int, int)), where str is the url, on imgur and
            the tuples are the dimensions of the image (width, height).
        Raises:
           LatexParsingException : there was an issue parsing the document
        """
        default_doc = []
        # populate doc with the appropriate problem
        for line in problem[0]:
            # these first two statements are for wrapping the title around in a minipage which allows
            # the problem to be generated on one page and doesn't invoke \newpage
            if line == '\\begin{document}':
                default_doc.append(NoEscape(line))
                default_doc.append(NoEscape('\\begin{minipage}{\\textwidth}'))
            elif line == '\\maketitle':
                default_doc.append(NoEscape(line))
                default_doc.append(NoEscape('\\end{minipage}'))
            elif line == '\\end{itemize}':
                for line2 in problem[1]:
                    default_doc.append(NoEscape(line2))
                default_doc.append(NoEscape(line))
            else:
                default_doc.append(NoEscape(line))

        doc_class_line = NoEscape(default_doc[0])
        use_pkg_line = NoEscape(default_doc[1])
        # skip twocolumn since it makes the problem look spread awfully
        opts = filter(lambda pkg: pkg != 'twocolumn', doc_class_line[doc_class_line.find('[') + 1: doc_class_line.find(']')].split(','))
        args = NoEscape(doc_class_line[doc_class_line.find('{') + 1: doc_class_line.find('}')])
        doc = Document(documentclass=Command('documentclass', options=opts, arguments=args))
        # load packages
        doc.packages = [Package(i) for i in use_pkg_line[use_pkg_line.find('{') + 1: use_pkg_line.find('}')].split(',')]
        # position right after \begin{document}
        it = 4
        while default_doc[it].strip() != '\end{document}':
            doc.append(NoEscape(default_doc[it]))
            it += 1
        # fail safe for future problems which may not parse correctly
        try:
            doc.generate_pdf('default', compiler="pdflatex")
        except:
            raise LatexParsingException

        # These are normal Linux commands that are used to convert the pdf
        # file created by pylatex into a snippet
        os.system("pdfcrop default.pdf")
        os.system("pdftoppm default-crop.pdf|pnmtopng > default.png")
        path = os.path.abspath('default.png')
        uploaded_image = self._client.upload_image(path, title="LaTeX")
        return uploaded_image.link, OnlineImage.get_local_image_info(path)
def test():
    doc = Document()
    Subsection('Only a single string', data='Some words')

    sec1 = Section('Only contains one subsection', data='Subsection')

    sec2 = Section('Only a single italic command', data=Command('textit',
                                                                'Hey'))
    sec2.append('something else that is not italic')
    doc.append(sec1)
    doc.append(sec2)

    doc.generate_pdf()
示例#39
0
文件: args.py 项目: markdoerr/PyLaTeX
def test_document():
    doc = Document(
        default_filepath="default_filepath",
        documentclass="article",
        fontenc="T1",
        inputenc="utf8",
        lmodern=True,
        data=None,
    )

    doc.append("Some text.")

    doc.generate_tex(filepath="")
    doc.generate_pdf(filepath="", clean=True)
示例#40
0
def test_document():
    doc = Document(
        default_filepath='default_filepath',
        documentclass='article',
        fontenc='T1',
        inputenc='utf8',
        lmodern=True,
        data=None,
    )

    repr(doc)

    doc.append('Some text.')

    doc.generate_tex(filepath='')
    doc.generate_pdf(filepath='', clean=True)
示例#41
0
文件: args.py 项目: rfilmyer/PyLaTeX
def test_document():
    doc = Document(
        default_filepath='default_filepath',
        documentclass='article',
        fontenc='T1',
        inputenc='utf8',
        author='',
        title='',
        date='',
        data=None,
        maketitle=False
    )

    doc.append('Some text.')

    doc.generate_tex(filepath='')
    doc.generate_pdf(filepath='', clean=True)
示例#42
0
def generate_hr_tex(G, matchings, output_dir, stats_filename):
    """
    print statistics for the resident proposing stable,
    max-cardinality popular, and popular amongst max-cardinality
    matchings as a tex file
    :param G: graph
    :param matchings: information about the matchings
    """
    # create a tex file with the statistics
    doc = Document('table')
    # M_s = matching_algos.stable_matching_hospital_residents(graph.copy_graph(G))

    # add details about the graph, |A|, |B|, and # of edges
    n1, n2, m = len(G.A), len(G.B), sum(len(G.E[r]) for r in G.A)
    with doc.create(Subsection('graph details')):
        with doc.create(Tabular('|c|c|')) as table:
            table.add_hline()
            table.add_row('n1', n1)
            table.add_hline()
            table.add_row('n2', n1)
            table.add_hline()
            table.add_row('m', m)
        table.add_hline()

    with doc.create(Subsection('general statistics')):
        with doc.create(Tabular('|c|c|c|c|')) as table:
            table.add_hline()
            table.add_row(('description', 'size', 'bp', 'bp ratio'))
            for desc in matchings:
                M = matchings[desc]
                sig = signature(G, M)
                msize = matching_utils.matching_size(G, M)
                bp = matching_utils.unstable_pairs(G, M)
                table.add_hline()
                table.add_row((desc, msize, len(bp), len(bp)/(m - msize)))
            table.add_hline()

    # statistics w.r.t. set A
    stats_for_partition(G, matchings, doc)

    # statistics w.r.t. set B
    # stats_for_partition(G, matchings, doc, False)

    stats_abs_path = os.path.join(output_dir, stats_filename)
    doc.generate_pdf(filepath=stats_abs_path, clean_tex='False')
    doc.generate_tex(filepath=stats_abs_path)
def doit(outfile = 'summary', ndim=3, action=True):
    if action == False:
        print(outfile, ndim)
        return

    if ndim == 3:
        resfile = '05aperture_results_3d.txt'
        statfile = '3d_cluster_statistics.txt'
    elif ndim == 2:
        resfile = '05aperture_results_2d.txt'
        statfile = 'cluster_statistics.txt'
        
    # generate blank LaTeX doc
    geometry_options = {"tmargin": "1cm", "lmargin": "2cm"}
    doc = Document(geometry_options=geometry_options)

    # insert some introductory material
    dirname = os.getcwd()
    doc.append('Clustering output, found in')
    doc.append(dirname)

    # get the K-means section of results table and insert into the document
    with doc.create(Section('K-means results')):
        tmptex, ncl_list = get_stats(resfile, 'kmeans', oldcols_results, newcols_results, None, None)
        doc.append(tmptex)
        doc.append(NewPage())
    
        # add the individual K-means runs
        add_sections_to_doc(ncl_list, 'kmeans', doc, statfile, ndim)

    # now the intro material for meanshift
    # get the results table and insert into the document
    with doc.create(Section('Meanshift results')):
        tmptex, ncl_list = get_stats(resfile, 'meanshift', oldcols_res_ms, newcols_res_ms, None, None)
        doc.append(tmptex)
        doc.append(NewPage())

        # add the individual meanshift runs
        add_sections_to_doc(ncl_list, 'meanshift', doc, statfile, ndim)
            
    # turn the LaTex into a PDF
    doc.generate_tex(filepath=outfile)
    doc.generate_pdf(outfile, clean_tex=False)
    
    # all done!
    return
示例#44
0
def main(fname, width, *args, **kwargs):
    doc = Document(fname)
    doc.packages.append(Package('geometry', options=['left=2cm', 'right=2cm']))

    doc.append('Introduction.')

    with doc.create(Section('I am a section')):
        doc.append('Take a look at this beautiful plot:')

        with doc.create(Figure(position='htbp')) as plot:
            plot.add_plot(width=NoEscape(width), *args, **kwargs)
            plot.add_caption('I am a caption.')

        doc.append('Created using matplotlib.')

    doc.append('Conclusion.')

    doc.generate_pdf()
示例#45
0
def test():
    doc = Document('jobname_test', title='Jobname test', maketitle=True)
    doc.generate_pdf()

    assert os.path.isfile('jobname_test.pdf')

    os.remove('jobname_test.pdf')

    folder = 'tmp_jobname'
    os.makedirs(folder)
    path = os.path.join(folder, 'jobname_test_dir')

    doc = Document(path, title='Jobname test dir', maketitle=True)
    doc.generate_pdf()

    assert os.path.isfile(path + '.pdf')

    shutil.rmtree(folder)
示例#46
0
文件: tabus.py 项目: JelteF/PyLaTeX
def genenerate_tabus():
    geometry_options = {
        "landscape": True,
        "margin": "1.5in",
        "headheight": "20pt",
        "headsep": "10pt",
        "includeheadfoot": True
    }
    doc = Document(page_numbers=True, geometry_options=geometry_options)

    # Generate data table with 'tight' columns
    fmt = "X[r] X[r] X[r] X[r] X[r] X[r]"
    with doc.create(LongTabu(fmt, spread="0pt")) as data_table:
        header_row1 = ["Prov", "Num", "CurBal", "IntPay", "Total", "IntR"]
        data_table.add_row(header_row1, mapper=[bold])
        data_table.add_hline()
        data_table.add_empty_row()
        data_table.end_table_header()
        data_table.add_row(["Prov", "Num", "CurBal", "IntPay", "Total",
                            "IntR"])
        row = ["PA", "9", "$100", "%10", "$1000", "Test"]
        for i in range(40):
            data_table.add_row(row)

    with doc.create(Center()) as centered:
        with centered.create(Tabu("X[r] X[r]", spread="1in")) as data_table:
            header_row1 = ["X", "Y"]
            data_table.add_row(header_row1, mapper=[bold])
            data_table.add_hline()
            row = [randint(0, 1000), randint(0, 1000)]
            for i in range(4):
                data_table.add_row(row)

    with doc.create(Center()) as centered:
        with centered.create(Tabu("X[r] X[r]", to="4in")) as data_table:
            header_row1 = ["X", "Y"]
            data_table.add_row(header_row1, mapper=[bold])
            data_table.add_hline()
            row = [randint(0, 1000), randint(0, 1000)]
            for i in range(4):
                data_table.add_row(row)

    doc.generate_pdf("tabus", clean_tex=False)
示例#47
0
class TrainingDocumentWriter:

    def __init__(self, title):
        self.title = title
        self.doc = Document(title)
        self.doc.packages.append(Package('geometry', options=['a4paper', 'top=2cm', 'bottom=2.5cm', 'left=2cm', 'right=2cm']))
        self.doc.packages.append(Package('titlesec', options=['sf']))
        self.doc.packages.append(Package('lmodern'))
        self.doc.append(Command('sffamily'))

        return


    def append_plot(self, pyplot, caption=''):
        with self.doc.create(Plt(position='htbp')) as plot:
            plot.add_plot(pyplot, width=ur'\textwidth')
            if caption!='':
                plot.add_caption(caption)

        return

    def append_section(self, section_title='', content=''):
        with self.doc.create(Section(section_title)):
            if content!='':
                self.doc.append(content)
        return

    def generate_pdf(self,filename=u'', clean=True, compiler='pdflatex'):

        #This is a workaround to save the generated pdf in a different directory (not in working dir)
        cur_path = os.getcwd()
        dirlist = filename.split('/')
        os.chdir(os.path.dirname(filename)) #cd to specified directory

        #Remove possible existing file extension (.pdf)
        if '.' in filename:
            self.doc.generate_pdf(dirlist[len(dirlist)-1].split('.')[0])
        else:
            self.doc.generate_pdf(dirlist[len(dirlist)-1])

        os.chdir(cur_path) #cd to original working directory

        return
示例#48
0
文件: utils.py 项目: pylipp/mscthesis
def show_pdf(filename):
    """
    Compiles a simple tex document that the matplotlib2tikz-generated figure 'filename' is embedded
    in. Displays pdf.

    :param filename | Name of input tex snippet (without extension)
    """
    from pylatex import Document, Figure, Command, Package
    document = Document()
    document.packages.append(Package('pgfplots'))
    with document.create(Figure(placement='ht')) as fig:
        fig.append(Command("centering"))
        fig.append(Command("input", "../figures/{}.tex".format(filename)))
        fig.add_caption("Test printing.")

    document.generate_pdf(clean=True, clean_tex=True)

    from subprocess import call
    call(['evince', "../figures/default_filepath.pdf"])
示例#49
0
def generate_eva_report():
		"""
    Generate a report which contains the evacution time for every test
    """
		geometry_options = {
		"head": "40pt",
		"margin": "0.5in",
		"bottom": "0.6in",
		"includeheadfoot": True
		}
		doc = Document(geometry_options=geometry_options)

		## Define style of report
		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)

		## Apply Pagestyle
		doc.change_document_style("reportStyle")

		## Create table
		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()

		## Write the results of 3 tests in table
		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)
示例#50
0
def generate_heuristic_tex(G, matchings, output_dir, stats_filename):
    """
    print statistics for the hospital proposing heuristic as a tex file
    :param G: graph
    :param matchings: information about the matchings
    """
    # create a tex file with the statistics
    doc = Document('table')

    # add details about the graph, |A|, |B|, and # of edges
    n1, n2, m = len(G.A), len(G.B), sum(len(G.E[r]) for r in G.A)
    with doc.create(Subsection('graph details')):
        with doc.create(Tabular('|c|c|')) as table:
            table.add_hline()
            table.add_row('n1', n1)
            table.add_hline()
            table.add_row('n2', n1)
            table.add_hline()
            table.add_row('m', m)
        table.add_hline()

    M_s = matching_algos.stable_matching_hospital_residents(graph.copy_graph(G))
    with doc.create(Subsection('Size statistics')):
        with doc.create(Tabular('|c|c|c|c|c|c|c|')) as table:
            table.add_hline()
            table.add_row(('description', 'size', 'bp', 'bp ratio', 'block-R',
                           'rank-1', 'deficiency'))
            for desc in matchings:
                M = matchings[desc]
                sig = signature(G, M)
                bp = matching_utils.unstable_pairs(G, M)
                msize = matching_utils.matching_size(G, M)
                table.add_hline()
                table.add_row((desc, msize, len(bp), len(bp)/(m - msize),
                               len(blocking_residents(bp)),
                               sum_ranks(sig, (1,)), #sum_ranks(sig, (1, 2, 3)),
                               total_deficiency(G, M_s)))
            table.add_hline()

    stats_abs_path = os.path.join(output_dir, stats_filename)
    doc.generate_pdf(filepath=stats_abs_path, clean_tex='False')
    doc.generate_tex(filepath=stats_abs_path)
示例#51
0
def george_report(csv, title):
	# get todays date
	today = datetime.today().date()
	#threshold = date(today.year, today.month, 1)
	threshold = date(today.year, today.month-1, 1)

	# Load data
	data_set = load_data(csv)

	# Start LaTex Doc
	doc = Document(title=title, date=today, author='Ken Payne [kenpay@]', maketitle=True)
	#doc.packages.append(Command('usepackage', options=Options('a4paper'), arguments=Arguments('geometry')))
	doc.packages.append(Command('renewcommand', arguments=Arguments('\\familydefault','\sfdefault')))
	doc.packages.append(Command('usepackage', arguments=Arguments('caption, setspace')))
	doc.packages.append(Command('captionsetup', arguments=Arguments('font={large, stretch=1.3}')))
	#doc.packages.append(Command('usepackage', arguments=Arguments('showframe')))
	doc.packages.append(Command('usepackage', arguments=Arguments('geometry'), options=Options('top=1in', 'bottom=1in', 'left=1in', 'right=1in')))
	doc.packages.append(Command('usepackage', arguments=Arguments('tocloft')))
	doc.packages.append(Command('renewcommand', arguments=Arguments('\cftsecleader}{\cftdotfill{\cftdotsep}')))


	# Report Sections
	# Table of Contents
	doc.append(Command('tableofcontents'))
	# Overview
	overview(doc, data_set, threshold)
	# Fast Movers
	doc.append(Command('clearpage'))
	fast_movers(doc, data_set, 100, threshold, 500)
	# Churn
	doc.append(Command('clearpage'))
	churn(doc, data_set, 5, threshold, 500)
	# Thresholds
	doc.append(Command('clearpage'))
	multi_thresholds(doc, data_set, threshold, deep_dive_thresholds)

	#doc.generate_tex()
	doc.generate_pdf()

	# Clean Up
	cleardirs(".")
示例#52
0
def generate_labels():
    geometry_options = {"margin": "0.5in"}
    doc = Document(geometry_options=geometry_options)

    doc.change_document_style("empty")

    for i in range(10):
        with doc.create(MiniPage(width=r"0.5\textwidth")):
            doc.append("Vladimir Gorovikov")
            doc.append("\n")
            doc.append("Company Name")
            doc.append("\n")
            doc.append("Somewhere, City")
            doc.append("\n")
            doc.append("Country")

        if (i % 2) == 1:
            doc.append(VerticalSpace("20pt"))
            doc.append(LineBreak())

    doc.generate_pdf("minipage", clean_tex=False)
示例#53
0
def test():
    doc = Document('jobname_test', data=['Jobname test'])
    doc.generate_pdf()

    assert os.path.isfile('jobname_test.pdf')

    os.remove('jobname_test.pdf')

    folder = 'tmp_jobname'
    os.makedirs(folder)
    path = os.path.join(folder, 'jobname_test_dir')

    doc = Document(path, data=['Jobname test dir'])
    doc.generate_pdf()

    assert os.path.isfile(path + '.pdf')
    shutil.rmtree(folder)

    folder = 'tmp_jobname2'
    os.makedirs(folder)
    path = os.path.join(folder, 'jobname_test_dir2')

    doc = Document(path, data=['Jobname test dir'])
    doc.generate_pdf(os.path.join(folder, ''))

    assert os.path.isfile(path + '.pdf')

    shutil.rmtree(folder)
示例#54
0
    def handle_request(self, latex_expr):
        """Uploads LaTeX formated equations to imgur and returns a URL.

        Args:
            latex_expr: string that is to converte to LaTeX, requires that string is enclosed by $.
            >>> handle_request("$\int \sqrt{1+\cos x + \sin x} dx$")
        Returns:
            A tuple (str, (int, int)), where str is the url, on imgur and
            the tuples are the dimensions of the image (width, height).
        """
        # create a bare bones latex document with only the one line specified from the user in the document.
        doc = Document(documentclass='minimal')
        doc.packages = [Package(NoEscape(i)) for i in self.packages.split(',')]
        doc.append(NoEscape(latex_expr))
        doc.generate_pdf('default', compiler_args=['-no-shell-escape', ], compiler="pdflatex", clean=True, clean_tex=True)
        # These are normal Linux commands that are used to convert the pdf
        # file created by pylatex into a snippet
        os.system("pdfcrop default.pdf")
        os.system("pdftoppm default-crop.pdf|pnmtopng > default.png")
        path = os.path.abspath('default.png')
        uploaded_image = self._client.upload_image(path, title="LaTeX")
        return uploaded_image.link, OnlineImage.get_local_image_info(path)
示例#55
0
文件: config.py 项目: JelteF/PyLaTeX
def main():
    cf.active = cf.Version1()
    doc = Document(data=NoEscape(lorem))
    doc.generate_pdf('config1_with_indent', clean_tex=False)

    cf.active = cf.Version1(indent=False)
    doc = Document(data=NoEscape(lorem))
    doc.generate_pdf('config2_without_indent', clean_tex=False)

    with cf.Version1().use():
        doc = Document(data=NoEscape(lorem))
        doc.generate_pdf('config3_with_indent_again', clean_tex=False)

    doc = Document(data=NoEscape(lorem))
    doc.generate_pdf('config4_without_indent_again', clean_tex=False)
示例#56
0
def generate_docs(config):
    """
        Function used to generate two pdf:

        -results.pdf: which shows all statistics about each formula with each
         benchmarked method.

        -summary.pdf: which count the number of times that each method is
         better than another.
    """
    # Let's create the documents (result & summary)
    doc = Document(documentclass='standalone')
    doc.packages.append(Package('amsmath'))
    doc.packages.append(Package('color'))
    doc.packages.append(Package('colortbl'))
    doc2 = Document(documentclass='standalone')

    # Declare colors in result document
    doc.append(DefineColor(
        arguments=Arguments('Gray', 'rgb', '0.7, 0.7, 0.7')))
    doc.append(DefineColor(arguments=Arguments('Green', 'rgb', '0.4, 1, 0.4')))
    doc.append(DefineColor(arguments=Arguments('Red', 'rgb', '0.8, 0, 0')))
    doc.append(DefineColor(arguments=Arguments('Yelw', 'rgb', '1, 0.98, 0.4')))
    doc.append(DefineColor(arguments=Arguments('Purpl', 'rgb', '1, 0.6, 1')))

    # Create Table with format : True is result format, False is summary format
    table = Tabular(add_fmt(len(config.l), True))
    table2 = Tabular(add_fmt(len(config.l), False))

    # Write everything
    write_results(table, config)
    write_summary(table2, config)

    # Output PDF
    doc.append(table)
    doc2.append(table2)
    doc.generate_pdf('results')
    doc2.generate_pdf('summary')
示例#57
0
文件: header.py 项目: JelteF/PyLaTeX
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)
def create_pdf(recipes):
    doc = Document()
    doc.packages.append(Package("hyperref", options="hidelinks"))

    doc.append("\\begin{titlepage}\n"
               "\\centering\n"
               "{\\scshape\\Huge\\textbf The Greater Book of Transmutation \\par}\n"
               "\\vspace{1.5cm}\n"
               "{\\scshape\\large How to make almost anything in a few easy steps \\par}\n"
               "\\vspace{5.5cm}\n"
               "{\\large A Procedurally Generated DIY Book \\par}\n"
               "{\\large for the \href{https://github.com/dariusk/NaNoGenMo-2015}{NaNoGenMo 2015} \\par}\n"
               "\\vspace{0.5cm}\n"
               "{\\large by \\href{http://dragonlab.de}{Tobias Wehrum} \\par}\n"
               "\\vfill\n"
               "{\\scriptsize using data by: \\par}\n"
               "\\vspace{0.3cm}\n"
               "{\\scriptsize\\href{http://web.usf.edu/FreeAssociation}{Nelson, D. L., McEvoy, C. L., \\& Schreiber, T. A. (1998). The University of South Florida word association, rhyme, and word fragment norms}\\par}\n"
               "\\vspace{0.3cm}\n"
               "{\\scriptsize\\href{https://www.englishclub.com/vocabulary/nouns-uncountable-list.htm}{English Club: Uncountable Nouns List}\\par}\n"
               "\\vspace{0.3cm}\n"
               "{\\scriptsize\\href{http://archives.nd.edu/whitaker/dictpage.htm}{LATIN-ENGLISH DICTIONARY WORDLIST Version 1.97FC by William Whitaker}\\par}\n"
               "\\vspace{0.5cm}\n"
               "\\end{titlepage}\n"
               "\n"
               "\\setcounter{tocdepth}{1}\n"
               "\\renewcommand*\\contentsname{How to make...}\n"
               "\\tableofcontents\n"
               "\\newpage");

    for r in recipes:
        r.print_to_doc(doc)

    try:
        os.remove("TheGreaterBookOfTransmutation.toc")
    except Exception as err:
        traceback.print_tb(err.__traceback__)

    try:
        doc.generate_pdf("TheGreaterBookOfTransmutation")
    except Exception as err:
        traceback.print_tb(err.__traceback__)

    try:
        doc.generate_tex("TheGreaterBookOfTransmutation")
    except Exception as err:
        traceback.print_tb(err.__traceback__)