def exportar_latex(self, ruta=''):
		doc = Document()

		###### encabezado
		# import pdb
		
		# archi = open('caratula.tex', 'r')
		# archivo = [x for x in archi]
		# pdb.set_trace()
		# doc.append(NoEscape('Aca va a ir el encavesado'))

		###### encabezado
		
		with doc.create(Section('{} #{}'.format(InstanciaPrueba.titulo ,self.id))):
			for numero in range(0, len(self.ejercicios_instanciados)):
				doc.append(self.ejercicios_instanciados[numero].latex(numero + 1))

		doc.generate_pdf(os.path.join(ruta, str(self.id)), clean_tex=True)
예제 #2
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(Plt(position='htbp')) as plot:
            plot.add_plot(pyplot, width=width, *args, **kwargs)
            plot.add_caption('I am a caption.')

        doc.append('Created using matplotlib.')

    doc.append('Conclusion.')

    doc.generate_pdf()
예제 #3
0
    def test_adjustbox(self):
        table = Table()
        name = "test_adjustbox"
        caption = "caption"
        input_tex = table.create_input_latex(df,
                                             name,
                                             caption=caption,
                                             above=False,
                                             adjustbox=True)

        # create document for testing input statement
        doc = Document()
        doc.append(input_tex)
        doc.preamble.append(NoEscape(r"\usepackage{booktabs}"))
        doc.preamble.append(NoEscape(r"\usepackage{zref-user}"))
        doc.preamble.append(NoEscape(r"\usepackage{adjustbox}"))
        # doc.generate_tex(f"Latex/{name}")
        doc.generate_pdf(f"Latex/{name}", clean_tex=False)
예제 #4
0
def main(fname, width, *args, **kwargs):
    geometry_options = {"right": "2cm", "left": "2cm"}
    doc = Document(fname, geometry_options=geometry_options)

    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(clean_tex=False)
예제 #5
0
def displaylatex(latexstring, filepath):
    """
        takes in a string of LaTeX latexstring, and a filepath
        (with no extension), and outputs a rendered pdf version
        of the LaTeX to the filepath + .pdf
    """
    doc = Document('basic', page_numbers=False, font_size='LARGE')
    doc.preamble.append(Command('usepackage', 'amsmath'))
    doc.preamble.append(Command('usepackage', 'geometry'))
    doc.preamble.append(Command('pagestyle', 'empty'))
    doc.preamble.append(
        NoEscape(r'\geometry{paperwidth=2.5in, paperheight=2.5in,'
                 r'margin=0.1in, hoffset=-0.2in}'))
    # NoEscape renders \'s properly instead of converting to \backslash
    doc.append(NoEscape(latexstring))
    doc.generate_pdf(filepath, clean_tex=False)
    # remove generated tex file
    os.system(f'rm {filepath+".tex"}')
예제 #6
0
 def __init__(self, mealplan, folder=".") -> None:
     self.mealplan = mealplan
     self.doc = Document(
         # f"{folder}/{self.mealplan._savename}",
         f"{folder}/tex/{self.mealplan._savename}",
         documentclass=Command("documentclass", "article"),
         fontenc=None,
         inputenc=None,
         font_size="normalsize",
         lmodern=False,
         textcomp=False,
         microtype=None,
         page_numbers=False,
         indent=None,
         geometry_options=None,
         data=None,
     )
     self.folder = folder
예제 #7
0
def plot_circuit(circuit):
    tex = circuit_to_latex_using_qcircuit(circuit)
    doc = Document(documentclass='standalone',
                   document_options=NoEscape(
                       'border=25pt,convert={density=300,outext=.png}'))
    doc.packages.append(Package('amsmath'))
    doc.packages.append(Package('qcircuit'))
    doc.append(NoEscape(tex))
    tmp_folder = mkdtemp()
    doc.generate_tex(tmp_folder + '/circuit')
    proc = subprocess.Popen(
        ['pdflatex', '-shell-escape', tmp_folder + '/circuit.tex'],
        cwd=tmp_folder)
    proc.communicate()
    image = plt.imread(tmp_folder + '/circuit.png')
    shutil.rmtree(tmp_folder)
    plt.axis('off')
    return plt.imshow(image)
예제 #8
0
 def resetDoc(self):
     """Adds packages and preamble to the document
     when it is to be regenerated. Clears previous entries.
     """
     self.doc = Document()
     pkgs_to_add = [ 'booktabs','hyperref','lipsum','microtype', 'graphicx',\
                     'nicefrac','url','bookmark','tabularx', 'svg']
     pream_to_add = {
         'title': f'{self.title}',
         'author': f'{self.author}',
         'date': f'{self.date}'
     }
     for pkg in pkgs_to_add:
         self.doc.packages.append(Package(pkg))
     for pa in pream_to_add:
         self.doc.preamble.append(Command(pa, pream_to_add[pa]))
     self.doc.append(NoEscape(r'\maketitle'))
     return
예제 #9
0
def launchReport(nb, nbPca, nbPerf, varName, pcs, correl, algorithm):
    loadings = []
    bestAndWorst = []
    stdDev = []
    pca = []
    for i in range(nb):
        load = []
        if algorithm[1]:
            for j in range(nbPerf):
                for k in range(nbPca):
                    load.append(
                        os.path.join(
                            os.path.dirname(__file__),
                            'plot\loadings\perf' + str(j) + 'var' +
                            str(i + 1) + 'PC' + str(k + 1) + '.png'))
            loadings.append(load)
        if algorithm[0]:
            pca.append(
                os.path.join(
                    os.path.dirname(__file__),
                    'plot\PCArepresentation\PCsVar' + str(i + 1) + '.png'))
        if algorithm[2] or algorithm[3]:
            for j in range(nbPca):
                if algorithm[2]:
                    bestAndWorst.append(
                        os.path.join(
                            os.path.dirname(__file__),
                            'plot\PcaBestworst\Var' + str(i + 1) + 'PC' +
                            str(j + 1) + '.png'))
                if algorithm[3]:
                    stdDev.append(
                        os.path.join(
                            os.path.dirname(__file__),
                            'plot\PCAstdDeviation\Var' + str(i + 1) +
                            'stdDeviationPC' + str(j + 1) + '.png'))
    # Basic document
    geometry_options = {"head": "40pt", "margin": "1in", "bottom": "0.6in"}
    doc = Document('report/sportAnalysis', geometry_options=geometry_options)
    doc.packages.append(Package('float'))

    fillPca(doc, pca, loadings, pcs, bestAndWorst, stdDev, varName, correl,
            nbPerf, nbPca, nb, algorithm)

    doc.generate_pdf(clean_tex=False)
예제 #10
0
    def test_four(self):
        doc = Document()
        with doc.create(Figure()) as fig:

            with fig.create(
                    SubFigure(width=NoEscape(r"0.48\textwidth"))) as left:
                name = "left"
                plt.figure()
                plt.plot(x, y, label="l")
                plt.legend()
                left.add_plot(name, caption=name)
                plt.close()

            with fig.create(
                    SubFigure(width=NoEscape(r"0.48\textwidth"))) as right:
                name = "right"
                plt.figure()
                plt.plot(x, y, label="r")
                plt.legend()
                right.add_plot(name, caption=name)
                plt.close()

            fig.append("\n")

            with fig.create(
                    SubFigure(width=NoEscape(r"0.48\textwidth"))) as left2:
                name = "left2"
                plt.figure()
                plt.plot(x, y, label="l2")
                plt.legend()
                left2.add_plot(name, caption=name)
                plt.close()

            with fig.create(
                    SubFigure(width=NoEscape(r"0.48\textwidth"))) as right2:
                name = "right2"
                plt.figure()
                plt.plot(x, y, label="r2")
                plt.legend()
                right2.add_plot(name, caption=name)
                plt.close()

            fig.add_caption("full")
        doc.generate_tex("Latex/foursubfigures")
예제 #11
0
    def on_begin(self, data: Data) -> None:
        exp_name = self.system.summary.name
        if not exp_name:
            raise RuntimeError("Traceability reports require an experiment name to be provided in estimator.fit()")
        # Convert the experiment name to a report name (useful for saving multiple experiments into same directory)
        report_name = "".join('_' if c == ' ' else c for c in exp_name
                              if c.isalnum() or c in (' ', '_')).rstrip().lower()
        report_name = re.sub('_{2,}', '_', report_name)
        self.report_name = report_name or 'report'
        # Send experiment logs into a file
        log_path = os.path.join(self.figure_dir, f"{report_name}.txt")
        if self.system.mode != 'test':
            # If not running in test mode, we need to remove any old log file since it would get appended to
            with contextlib.suppress(FileNotFoundError):
                os.remove(log_path)
        self.log_splicer = LogSplicer(log_path)
        self.log_splicer.__enter__()
        # Get the initialization summary information for the experiment
        self.config_tables = self.system.summary.system_config
        models = self.system.network.models
        n_floats = len(self.config_tables) + len(models)

        self.doc = Document(geometry_options=['lmargin=2cm', 'rmargin=2cm', 'tmargin=2cm', 'bmargin=2cm'])
        # Keep tables/figures in their sections
        self.doc.packages.append(Package(name='placeins', options=['section']))
        self.doc.preamble.append(NoEscape(r'\usetikzlibrary{positioning}'))

        # Fix an issue with too many tables for LaTeX to render
        self.doc.preamble.append(NoEscape(r'\maxdeadcycles=' + str(2 * n_floats + 10) + ''))
        self.doc.preamble.append(NoEscape(r'\extrafloats{' + str(n_floats + 10) + '}'))

        # Manipulate booktab tables so that their horizontal lines don't break
        self.doc.preamble.append(NoEscape(r'\aboverulesep=0ex'))
        self.doc.preamble.append(NoEscape(r'\belowrulesep=0ex'))
        self.doc.preamble.append(NoEscape(r'\renewcommand{\arraystretch}{1.2}'))

        self.doc.preamble.append(Command('title', exp_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'))

        # TOC
        self.doc.append(NoEscape(r'\tableofcontents'))
        self.doc.append(NoEscape(r'\newpage'))
예제 #12
0
    def test_label(self):
        fig = Figure()
        name = "test_label"
        caption = "caption"
        label = "label"
        plt.figure()
        plt.plot(x, y)

        input_tex = fig.create_input_latex(name,
                                           caption=caption,
                                           above=True,
                                           label=label)

        # create document for testing input statement
        doc = Document()
        doc.append(input_tex)
        doc.preamble.append(NoEscape(r"\usepackage{graphicx}"))
        doc.preamble.append(NoEscape(r"\usepackage{zref-user}"))
        doc.generate_pdf("Latex/test_label", clean_tex=False)
예제 #13
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.

    Raises:
        OSError, IOError: If cleanup fails.
    """
    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.preamble.append(Package('inputenc', options=['utf8']))
    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
예제 #14
0
def produce_latex(subfolder_under_diagram, latexpdfname):
    pic_path_list = []
    for dirname, dirnames, filenames in os.walk(dp.diagram_path +
                                                subfolder_under_diagram):
        # print path to all subdirectories first.
        for subdirname in dirnames:
            print(os.path.join(dirname, subdirname))

        # print path to all filenames.
        for filename in filenames:
            pic_path_list.append(os.path.join(dirname, filename))

    pic_path_list = natural_sort(pic_path_list)
    os.chdir(dp.latex_path)
    doc = Document(default_filepath=dp.latex_path + latexpdfname)
    doc.packages.append(Package('placeins', "section"))

    #breakpoint()

    with doc.create(Section("Simulation Plot")):
        doc.append("Width= " + str(rr.log_variable["width_wall_dp_unit"]) +
                   " diameter")
        doc.append("\nHeight= " +
                   str(rr.log_variable["z_length_create_dp_unit"]) +
                   " diameter")
        doc.append("\nPeriodic length in shear direction = " +
                   str(rr.log_variable["x_period_dp_unit"]) + " diameter")
        doc.append("\nSavage_number = " + str(rr.log_variable["Sa"]))
        doc.append("\nV_wall = " + str(
            float(rr.log_variable["in_velocity"]) /
            float(rr.log_variable["dp"])) + " diameter/second")

        for pic_path in pic_path_list:
            with doc.create(Figure(position='h!')) as pic:
                #breakpoint()
                pic.add_image(pic_path)
                pic.add_caption(NoEscape("\label{fig:epsart}"))

        doc.append(NoEscape("\\FloatBarrier"))

    doc.generate_pdf(clean_tex=False)

    os.chdir(rr.lammps_directory)
예제 #15
0
파일: tabus.py 프로젝트: tysoncung/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)
예제 #16
0
 def __init__(self, recipe, folder=".") -> None:
     self.recipe = recipe
     self.doc = Document(
         f"{folder}/tex/{self.recipe._savename}",
         documentclass=Command("documentclass",
                               arguments="standalone",
                               options="preview"),
         fontenc=None,
         inputenc=None,
         font_size="normalsize",
         lmodern=False,
         textcomp=False,
         microtype=None,
         page_numbers=False,
         indent=None,
         geometry_options=None,
         data=None,
     )
     self.folder = folder
    def test_single_sentence_pdf_with_fi_glyph(self):

        # LaTex font renders the fi in file as a single glyph, which is then read back as a
        # single unicode character.
        content = "Hello, world. I am a PDF file"

        pdf_file = Document(default_filepath=self.strip_pdf_file_extension(
            self.output_pdf),
                            page_numbers=False)

        pdf_file.append(content)
        pdf_file.generate_tex()
        pdf_file.generate_pdf(clean_tex=False)

        normalised_html = generate_normalised_html(self.output_pdf)
        soup = BeautifulSoup(normalised_html, 'html.parser')
        section = soup.section

        assert content in str(section.string)
예제 #18
0
    def dump(self, ass, fh=None):
        fh = super().get_fh(fh)

        doc = Document()

        self.build_preamble(doc, ass)
        self.build_questions(doc, ass)
        self.build_figures(doc, ass)

        make_key = self.make_key
        # if assignment has a make_key entry, use it instead
        if ass.meta.has('make_key'):
            make_key = ass.meta.make_key
        if make_key:
            self.build_key(doc, ass)

        fh.write(doc.dumps())

        return
예제 #19
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)
예제 #20
0
    def mk_tex(self, filename):
        # create he latex doc
        doc = Document()
        # Check to avoid index error and create the table border lines
        if self.table != []:
            size = len(self.table[0])
            header = '|l' * size
            header += '|'
        else:
            print('No values assigned to the table')
            return None

        # Fill the table and create a tex file in the New_Files Folder
        with doc.create(Tabular(header)) as table:
            table.add_hline()
            for row in self.table:
                table.add_row(row)
                table.add_hline()
        doc.generate_tex('../New_Files/' + filename)
        print("Succesfully Created", '../New_Files/' + filename + '.tex')
 def __init__(self, name):
     geometry_options = ['a4paper', "margin=0.2in", "landscape= True"]
     self.doc = Document(name,
                         geometry_options=geometry_options,
                         font_size='small')
     self.sections = {}
     self.results_values = {
         AVG_LATENCY: {},
         AVG_THROUGHPUT: {},
         Q09_LATENCY: {},
         Q09_THROUGHPUT: {},
         NUMA_NODE_0: {},
         NUMA_NODE_1: {},
         NUMA_NODE_2: {},
         NUMA_NODE_3: {},
         MBW_LOCAL: {},
         MBW_REMOTE: {}
     }
     self.experiment_types = []
     self.name = name
예제 #22
0
def GenerateArrowDiagram(filepath, params):
    doc = Document(documentclass="standalone", document_options=NoEscape("convert={density=300,size=1080x800,outext=.png}"))
    doc.packages.append(Package('amsmath'))
    doc.packages.append(Package('tikz'))
    tikztex = r"""\usetikzlibrary{arrows}
    \begin{tikzpicture}
    \draw[latex-] (-6.5,0) -- (6.5,0) ;
    \draw[-latex] (-6.5,0) -- (6.5,0) ;
    \foreach \x in  {-6,-4,-2,0,2,4,6}
    \draw[shift={(\x,0)},color=black] (0pt,3pt) -- (0pt,-3pt);
    \foreach \x in {-6,-4,-2,0,2,4,6}
    \draw[shift={(\x,0)},color=black] (0pt,0pt) -- (0pt,-3pt) node[below] 
    {$\x$};
    \draw[->] (0,1.0) -- ({:d},1.0);
    \draw[->] ({:d},0.5) -- ({:d},0.5);
    \draw[very thick    ] (0.92,0) -- (1.92,0);
    \end{tikzpicture}"""
    #print(tikztex)
    doc.append(NoEscape(tikztex.format(params['a'],params['a'],params['a']+params['b'])))
    doc.generate_pdf(filepath=filepath)
예제 #23
0
 def setuplatex(self):
     self.filename = self.id + '-' + time.strftime('%Y')
     self.documentclass = Command('documentclass',
                                  arguments='scrlttr2',
                                  options=self.docoptions)
     self.doc = Document(self.filename,
                         documentclass=self.documentclass,
                         fontenc='T1',
                         inputenc='utf8')
     self.doc.preamble.append(Command('input', latex_preamble))
     self.doc.preamble.append(Command('LoadLetterOption', 'template'))
     self.doc.preamble.append(
         Command('setkomavar',
                 arguments='subject',
                 extra_arguments=self.subject))
     self.doc.preamble.append(
         Command('setkomavar',
                 arguments='yourmail',
                 options=self.categroy[1],
                 extra_arguments=self.filename))
예제 #24
0
파일: Tex.py 프로젝트: SpudBoi/wheat
    def write(self):
        if os.path.exists("latex.aux"):
            os.remove("latex.aux")
            os.remove("latex.log")
            os.remove("latex.tex")
            os.remove("latex.pdf")
        else:
            print("The file does not exist")

        print(self.counter)
        self.code = self.ids.equation.text
        doc = Document(self.docname)
        self.fill_document(doc,self.code)
        try:
            print("it tried")
            doc.generate_pdf(filepath='Wheat/Notebook/Tex/', clean_tex = True, compiler='pdflatex') #not good with error
            print("it tried2")
            self.convert_image(False)
        except:
            pass
예제 #25
0
def dataframe_to_pdf(df, pdf_path):
    geometry_options = {"margin": "2.54cm", "includeheadfoot": True}
    doc = Document(page_numbers=True, geometry_options=geometry_options)

    num_cols = len(df.columns)

    # Generate data table
    with doc.create(LongTable("l " * num_cols)) as data_table:
        data_table.add_hline()
        data_table.add_row(list(df.columns.values))
        data_table.add_hline()
        for i in range(len(df.index)):
            row_list = df.iloc[i].values.tolist()
            if "SEP" in row_list[0]:
                data_table.add_hline()
            else:
                data_table.add_row(row_list)
        data_table.add_hline()

    doc.generate_pdf(pdf_path, clean_tex=False)
예제 #26
0
    def translate(self, filename: str):
        doc = Document('basic')

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

        doc.append(NoEscape("\\newcommand{\err}[1]{\\textit{#1}}"))  # !

        for block in self.blocks:
            doc.append(NoEscape(block.getOutput() + '\\\\'))

        babel = Package('babel', 'english, russian')
        fontenc = Package('fontenc', 'T2A')
        inputenc = Package('inputenc', 'utf8')
        doc.packages.items = [fontenc, inputenc, babel]

        doc.generate_tex(filename)
        try:
            doc.generate_pdf(filename, clean_tex=False)
        except Exception as e:
            print(e)
예제 #27
0
 def build_latex(
         evaluations: Dict[str, List[Metric]],
         file_name: str,
         invert_map: Dict[str, bool] = defaultdict(lambda: False),
         **kwargs,
 ):
     logger.info("Building LaTex Document")
     doc = Document("")
     section = Section("Evaluations")
     tables = [
         MetricTable.build_latex(evals,
                                 invert=invert_map[caption],
                                 caption=caption)
         for caption, evals in evaluations.items()
     ]
     doc.append(section)
     for table in tables:
         section.append(table)
     doc.generate_tex(filepath=file_name)
     logger.success("LaTex Document build success")
     return doc
예제 #28
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)
예제 #29
0
파일: main.py 프로젝트: tobiasli/photobook
    def generate_pdf_from_chapters(self, path, title) -> None:
        # TODO: Fix this!
        print('Generating pdf!')
        doc = Document(documentclass='book', document_options=['a4paper', '11pt'])
        doc.packages.append(Package('graphicx'))
        doc.default_filepath = path
        for chapter in self.chapters:
            with doc.create(Section(str(chapter.period))):
                for text in chapter.text:
                    doc.append(text.text_escape)
                for photo in chapter.photos:
                    doc.append(NoEscape(photo.latex))
            doc.append(NoEscape(r'\newpage'))

        doc.generate_pdf()
        doc.generate_tex()

        # doc = self.create_tex()
        # doc.default_filepath = path
        # doc.generate_pdf(title, clean=True, clean_tex=True)
        print('Done!')
예제 #30
0
def report_generator(save_path, attack_subsections, pdf=False):
    """Create a report out of multiple attack sections.

    Parameters
    ----------
    save_path : str
        Path to save the tex and pdf file of the report.
    attack_subsections : list
        List containing all attack subsections in the pentesting setting.
    pdf : bool
        If set, generate pdf out of latex file.
    """
    doc = Document(documentclass="article")
    doc.preamble.append(Command("usepackage", "graphicx"))
    doc.preamble.append(Command("usepackage", "subcaption"))
    doc.preamble.append(Command("usepackage", "geometry"))
    doc.preamble.append(Command("usepackage", "float"))
    doc.preamble.append(Command("geometry", "textwidth=180mm, textheight=240mm"))
    doc.preamble.append(Command("title", "Privacy Risk and Robustness Report"))
    doc.preamble.append(Command("date", NoEscape(r"\today")))
    doc.append(NoEscape(r"\maketitle"))

    # Group by attack type and preserve order
    order = [elm.attack_type for elm in attack_subsections if elm.attack_type]
    attack_subsections.sort(key=lambda elm: order.index(elm.attack_type))
    grouped_sections = [
        list(arr)
        for k, arr in groupby(attack_subsections, key=lambda elm: elm.attack_type)
    ]

    for i, attack in enumerate(grouped_sections):
        with doc.create(Section(attack[0].attack_name)):
            doc.append(descriptions[attack[0].attack_type])
            for subsection in attack:
                doc.append(subsection)

    if pdf:
        doc.generate_pdf(save_path + "/attack_report", clean_tex=False)
    else:
        doc.generate_tex(save_path + "/attack_report")