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()
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
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()
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()
def fill_document(self): """Add a section, a subsection and some text to the document.""" with self.create(Section('A section')): self.append('Some regular text and some ') self.append(italic('italic text. ')) with self.create(Subsection('A subsection')): self.append('Also some crazy characters: $&#{}')
def create_appendix(stat_map): doc = Document('Appendixx') doc.append(NoEscape(r'\appendix')) with doc.create( Section(NoEscape('Appendix F: Conjectures for $s=3$ to 50'))): for s in range(3, 51): print('s: ', s) exceptions_list = [({}, 0)] num_exceptions = 0 for k in range(1, s): print('k: ', k) exceptions, start_k = find_exceptions(s, k, stat_map) num_exceptions += len(exceptions) exceptions_list.append((exceptions, start_k)) doc.append( NoEscape(r'\begin{conjecture}\label{co:' + str(s) + r'}')) doc.append( NoEscape( r'If $m=' + str(s) + r'k+i$ where $0\le i\le ' + str(s - 1) + '$ then $f(m,' + str(s) + r')$ depends only on $k,i$ via a formula, given below')) if num_exceptions == 0: doc.append('.') else: doc.append( NoEscape(', with ' + str(num_exceptions) + ' exceptions (we will note the exceptions).')) doc.append(NoEscape('\n')) doc.append( NoEscape(r'\noindent' + '\n' r'\text{\bf{Case 0:}} $m=' + str(s) + 'k+0$ with $k\ge 1$. Then $f(' + str(s) + 'k,' + str(s) + ')=1$.')) doc.append(NoEscape('\n')) for i in range(1, s): numer, denom = fc_pattern(i, s) if numer is not None: exceptions, start_k = exceptions_list[i] pattern_frac = r'\frac{' + numer + '}{' + denom + '}' doc.append(NoEscape(r'\noindent')) doc.append( NoEscape(r'\text{\bf{Case ' + str(i) + ':}} $m=' + str(s) + 'k+' + str(i) + r'$ with $k\ge ' + str(start_k) + r'$. Then $f(' + str(s) + 'k+' + str(i) + ',' + str(s) + ')=' + pattern_frac + '$.')) if len(exceptions) != 0: exp_str = ' (Exception: ' for exp in exceptions.keys(): q, exp_type = exceptions[exp] exp_str += r'$f(' + str(exp.numerator) + ',' + str(exp.denominator) + ')=' \ + str(q) + r'$ ' + exp_type + ', ' doc.append(NoEscape(exp_str.strip(', ') + '.)')) doc.append(NoEscape('\n')) doc.append( NoEscape(r'\end{conjecture}' + '\n\n' + '--------------------\n')) doc.generate_tex('Appendix')
def do(): doc = Document() # create a bulleted "itemize" list like the below: # \begin{itemize} # \item The first item # \item The second item # \item The third etc \ldots # \end{itemize} with doc.create(Section('"Itemize" list')): with doc.create(Itemize()) as itemize: itemize.add_item("the first item") itemize.add_item("the second item") itemize.add_item("the third etc") # you can append to existing items itemize.append(Command("ldots")) # create a numbered "enumerate" list like the below: # \begin{enumerate} # \item The first item # \item The second item # \item The third etc \ldots # \end{enumerate} with doc.create(Section('"Enumerate" list')): with doc.create(Enumerate()) as enum: enum.add_item("the first item") enum.add_item("the second item") enum.add_item(NoEscape("the third etc \\ldots")) # create a labelled "description" list like the below: # \begin{description} # \item[First] The first item # \item[Second] The second item # \item[Third] The third etc \ldots # \end{description} with doc.create(Section('"Description" list')): with doc.create(Description()) as desc: desc.add_item("First", "The first item") desc.add_item("Second", "The second item") desc.add_item("Third", NoEscape("The third etc \\ldots")) doc.generate_pdf('lists', clean_tex=False)
def fill_document(): with open('./temp/explanations/explanations.json') as f: data = json.load(f) doc = Document() for element in data['elements']: date = element['date'] explanation = element['explanation'] picture_path = element['picture'] if date[2:4] == '01': month = 'January' elif date[2:4] == '02': month = 'February' elif date[2:4] == '03': month = 'March' elif date[2:4] == '04': month = 'April' elif date[2:4] == '05': month = 'May' elif date[2:4] == '06': month = 'June' elif date[2:4] == '07': month = 'July' elif date[2:4] == '08': month = 'August' elif date[2:4] == '09': month = 'September' elif date[2:4] == '10': month = 'October' elif date[2:4] == '11': month = 'November' elif date[2:4] == '12': month = 'December' else: month = 'Error: Invalid month' if int(date[4:]) < 10: day = date[-1] else: day = date[4:] if int(date[0:2]) < 95: year = '20' + date[0:2] else: year = '19' + date[0:2] with doc.create( Section(month + ' ' + day + ', ' + year, numbering=False)): doc.append( StandAloneGraphic(image_options=r'width=\textwidth', filename=picture_path)) doc.append(bold('\n\nExplanation:\n')) doc.append(explanation) doc.append(NewPage()) doc.generate_pdf('astronomy-picture-of-the-day', clean_tex=True)
def add_free_body_diagram(self): with self.doc.create(Section(self.tpdf.step_free_body_diagram_0)): with self.doc.create(Figure(position='H')) as fig_corpolivre: if self.sr.hinged and self.sr.roll: fig_corpolivre.add_image("figs\\diagram1", width='500px') elif self.sr.fixed: fig_corpolivre.add_image("figs\\diagram2", width='500px') fig_corpolivre.add_caption( NoEscape(self.tpdf.free_body_diagram_0_label))
def create_tex(self, doc): print('Generating latex!') with doc.create(Section('The year 2018')): doc.append('Here are some cool images from 2018!') for i, image in enumerate(self.photos.photos): with doc.create(Figure(position='h!')) as figure: figure.add_image(image.filepath, width='400px') figure.add_caption(f'Image nr {i} taken {image.timestampstr}') return doc
def index(): if request.method == 'POST': if not request.files.get('file', None): print('No file attached in request') return redirect(request.url) # list for file paths and extracted text extractedtext = [] files = request.files.getlist("file") for file in files: if allowed_file(file.filename): # save as temporary files for processing unique_filename = uuid.uuid4().urn[9:] + '.' + file.filename.rsplit('.', 1)[1].lower() filepath = os.path.join(os.environ['UPLOAD_FOLDER'] + "/" + unique_filename) file.save(filepath) # extract text from file extractedtext.append(extract_text(filepath)) # remove temporary file os.remove(filepath) # create latex document doc = Document(page_numbers=False, lmodern=False, fontenc=None, inputenc=None, textcomp=False) with doc.create(Section('Extracted text')): for page in extractedtext: for index in range(0, len(page), 1): doc.append(page[index] + '\n') doc.append('\n') # save temporary latex and pdf documents tempname = uuid.uuid4().urn[9:] temppath = os.path.join(os.environ['UPLOAD_FOLDER'], tempname) doc.generate_pdf(temppath, clean_tex=False) # create zip file with zipfile.ZipFile(temppath + '.zip','w', compression=zipfile.ZIP_DEFLATED) as zipf: zipf.write(temppath + '.pdf', "extracted_text.pdf") zipf.write(temppath + '.tex', "extracted_text.tex") # remove temporary files os.remove(temppath + '.pdf') os.remove(temppath + '.tex') @after_this_request def remove_file(response): os.remove(temppath + '.zip') return response return send_file(temppath + '.zip', mimetype = 'zip', attachment_filename= 'Extracted_Text.zip', as_attachment = True) return render_template('index.html')
def desolateEra(bookMax, chapterMax): novelTitle = "Desolate Era" author = "I Eat Tomatoes" baseURL = "http://www.wuxiaworld.com/desolate-era-index/de-book-%d-chapter-%d" B = bookMax 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(1, 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/span/strong/text()') for tit in title: title2 = unidecode(tit) Book = title2.split(', ') Book = Book[1] Chapter = title2.split(' - ') Chapter = Chapter[1] if c == 1: # 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 %d: %s' % (c, 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 write_wordfield_curve(self, doc, dta_holder, wf_cat=str()): if wf_cat == "None": pass else: with doc.create(Section("Word field development", numbering=True)) as wordField: wordField.append( "Word field development in the current book. The plot(s) below show how the presence of certain terms\ change with the narrative, from beginning to end.")
def write_weighted_degrees(self, doc, dta_holder): with doc.create(Section("weighted degrees", numbering=False)): index = 1 for weigthed_degree_tuple in dta_holder["network_parameters"][4]: with doc.create( Subsection("%s" % weigthed_degree_tuple[0], numbering=False)): doc.append(weigthed_degree_tuple[1])
def insert_answer(self, doc): with doc.create(Section(str(self))): # Generate the LaTeX code to insert each worked answer of this topic into the # document. Returns doc. doc.append(NoEscape(r'\begin{multicols}{2}')) doc.append(NoEscape(r'\begin{enumerate}[label=(\alph*)]')) for i in range(0, len(self.a)): # Initial fraction frac_string = r'\item $$ ' if self.a[i] != 0: frac_string += '%i ' % (self.a[i]) frac_string += r'\frac{%i}{%i} + ' % (self.a_num[i], self.a_den[i]) if self.b[i] != 0: frac_string += '%i ' % (self.b[i]) frac_string += r'\frac{%i}{%i} = ' % (self.b_num[i], self.b_den[i]) # Common denominator new_den = self.a_den[i] * self.b_den[i] if self.a_den[i] == self.b_den[i]: # Denominators are the same by chance - don't multiply them together new_den = self.a_den[i] frac_string += r'\frac{%i}{%i} + \frac{%i}{%i} =' % \ ((self.a[i] * self.a_den[i]) + self.a_num[i], new_den, (self.b[i] * self.b_den[i]) + self.b_num[i], new_den) # Add numerators new_num = (self.a[i] * self.a_den[i]) + self.a_num[i] + \ (self.b[i] * self.b_den[i]) + self.b_num[i] else: # Denominators are different - multiply the fractions to get a # common denominator between fractions frac_string += r'\frac{%i}{%i} + \frac{%i}{%i} =' % \ (self.b_den[i] * (self.a_num[i] + self.a_den[i] * self.a[i]), new_den, self.a_den[i] * (self.b_num[i] + self.b_den[i] * self.b[i]), new_den) # Add numerators new_num = self.b_den[i] * (self.a_num[i] + self.a_den[i] * self.a[i]) + \ self.a_den[i] * (self.b_num[i] + self.b_den[i] * self.b[i]) frac_string += r'\frac{%i}{%i} = ' % (new_num, new_den) # Simplify fraction final = Fraction(int(new_num), int(new_den)) if final.denominator > 1: frac_string += r'\frac{%i}{%i} $$' % (final.numerator, final.denominator) else: frac_string += r'%i $$' % final.numerator doc.append(NoEscape(frac_string)) doc.append(NoEscape(r'\end{enumerate}')) doc.append(NoEscape(r'\end{multicols}')) return doc
def create_pdf_document(fullnames, emails): doc = Document("users-details") with doc.create(Section("Users")): for subsection_title, data_list in zip(["Full names", "Emails"], [fullnames, emails]): with doc.create(Subsection(subsection_title)): for data in data_list: doc.append(data + "\n") doc.generate_pdf(clean_tex=False)
def build_all(subdirs, preamble="preamble.tex"): doc = d = make_doc(preamble) for subdir in subdirs: chap = re.search(r"\d+", subdir).group(0) with d.create(Section(chap, numbering=False)): exos, probs = build_chap(chap, preamble) d.append(Subsection("Exercises", numbering=False, data=exos)) if len(probs) > 0: d.append(Subsection("Problems", numbering=False, data=probs)) return doc
def append_radius_and_max_shear(self): with self.gen.doc.create(Section(self.gen.tpdf.radius_and_max_shear)): with self.gen.doc.create(Subsection(self.gen.tpdf.radius_and_max_shear_formula)): self.gen.pdf.add_equation( self.gen.tpdf.radius_var + r' \sqrt{(\frac{\sigma_x-\sigma_y}{2})^2 + \tau_xy ^ 2)}') with self.gen.doc.create(Subsection(self.gen.tpdf.radius_and_max_shear_solving)): self.gen.pdf.add_equation( self.gen.tpdf.radius_var + r' \sqrt{(\frac{' + fr'{self.res.sigma_x}-{self.res.sigma_y}' + '}{2})^2 +' + f'{self.res.tau_xy}' + '^ 2)}') self.gen.pdf.add_equation(self.gen.tpdf.radius_var + f'{append_result(self.res.max_shear)}')
def create_section(io_doc, i_specification_line, io_sections_dict, io_characteristic_bloc): if i_specification_line.has_section(): if i_specification_line.section not in io_sections_dict: with io_doc.create(Section(i_specification_line.section)): fill_section(io_doc, i_specification_line, io_sections_dict, io_characteristic_bloc) else: fill_section(io_doc, i_specification_line, io_sections_dict, io_characteristic_bloc)
def append_to_document(self, doc: Document, doc_answers: Enumerate) -> None: variable_dict = {} for variable in self.variables: variable_dict[variable.symbol] = variable.value parsed_text = QuestionParser(**variable_dict).parse(self.text) with doc.create(Section(parsed_text)): doc.append(bold('Verdadero\t\tFalso')) expr = BooleanParser(**variable_dict).parse(self.expression) doc_answers.add_item('VERDADERO' if expr else 'FALSO')
def comments(doc): """ Add comments (bullet points). """ with doc.create(Section('Comments', numbers=True)): with doc.create(Itemize()) as itemize: itemize.add_item(bullet_1) itemize.add_item(bullet_2) itemize.add_item(bullet_3) itemize.add_item(bullet_4)
def auto_comments(doc): """ Loop through bullets_std and add them to list. """ with doc.create(Section('Comments', numbers=True)): with doc.create(Itemize()) as itemize: for s in bullets_std: itemize.add_item(s) for s in bullets_nstd: itemize.add_item(s)
def latex(self, doc): [(doc.append(line), doc.append(lbr())) for line in self.strHeader().split('\n')] with doc.create(Section("Single Player Monster Stats")): [ Monster.applyModifiers(self.Diff.spMod()).latex(doc) for Monster in self.Monsters if Monster ] with doc.create(Section("Multiplayer Monster Stats")): [ Monster.applyModifiers(self.Diff.mpMod( self.Tail.mpDiff)).latex(doc) for Monster in self.Monsters if Monster ] with doc.create(Section("Quest Rewards")): [ self.REM[rem].latex(doc) for rem in self.Objective.REMID if rem != 0 ]
def append_to_document(self, doc: Document, doc_answers: Enumerate) -> None: variable_dict = {} for variable in self.variables: variable_dict[variable.symbol] = variable.value parsed_text = QuestionParser(**variable_dict).parse(self.text) with doc.create(Section(parsed_text)): doc.append('Respuesta: ') doc.append(LineBreak()) doc_answers.add_item('Respuesta de pregunta abierta')
def middle_fork(self): with self.create(Section('Middle Fork')) as section_mf: df = self.capacity.models['middle_fork'] mask = (df['prod_date'] >= self.dt_start) & (df['prod_date'] < self.dt_end) table_df = df.loc[mask] summary_table_mf = Tabular('ccc|ccc|ccc', row_height=.40, width=9, booktabs=True) avg_tablemaker(summary_table_mf, table_df, self.month1, self.month2, self.month3) self.append(summary_table_mf) with self.create(Figure(position='h!')) as mf_plot: mf_fig, (ax1) = plt.subplots(nrows=1, ncols=1, sharex=True, sharey=False, squeeze=True, figsize=(14, 4)) self.append(NoEscape(r'')) ax1.stackplot(self.x, df.base_volume, df.wedge_volume, df.offload_volume, df.gas_lift_volume, df.berry_volume, df.garden_gulch_volume, labels=[ 'Base', 'Wedge', 'Offload', 'Gas Lift', 'Berry', 'Garden Gulch' ], colors=[ 'blue', 'cornflowerblue', 'orange', 'gold', 'goldenrod', 'red' ]) ax1.plot(self.x, df.max_volume, label='Capacity') ax1.legend(loc='upper left') ax1.tick_params(labelsize=14) mf_plot.add_plot(width=NoEscape(r'1\textwidth')) table_mf = Tabular('ccc|ccc|ccc', row_height=.10, width=9, booktabs=True) table_mf.add_row('Date', 'Gas, MCF', 'Delta', 'Date', 'Gas, MCF', 'Delta', 'Date', 'Gas, MCF', 'Delta') table_mf.add_hline() tablemaker(table_mf, table_df.prod_date.astype(str).tolist(), table_df.forecast.values.tolist(), table_df.report_overflow.values.tolist(), self.month1, self.month2, self.month3) section_mf.append(table_mf) self.append(NewPage())
def gen(f_nm, n_ex, n_digits, digit_var, n_nums, n_cols): print("----- START -----") ttl = 'Column addition - ' + str(n_nums) + ' ' + str(n_digits) + '-digit values with ' + str(digit_var) + '-digit variance' q_doc = Document(geometry_options = pge_geom, lmodern=True) a_doc = Document(geometry_options = pge_geom, lmodern=True) with q_doc.create(Section("Questions: " + ttl, numbering=False)): q_doc.append('Solve the following questions!') with a_doc.create(Section("Answers: " + ttl, numbering=False)): a_doc.append('Answers to problem sheet') q_doc.add_color(name="cream", model="rgb", description=cream_clr_def) q_doc.append(Command('fontsize', arguments = ['16', '18'])) q_doc.append(Command('fontfamily', arguments = ['pcr'])) q_doc.append(Command('selectfont')) q_doc.append(FlushRight()) a_doc.add_color(name="cream", model="rgb", description=cream_clr_def) # Add statement table with a_doc.create(LongTabu("X[l] " * n_cols, row_height=2.0)) as a_tbl: with q_doc.create(LongTabu("X[r] " * n_cols, row_height=2.0)) as q_tbl: for i in range(round(n_ex/n_cols)): row = [' ' + str(n + i*n_cols) + '.' for n in range(0, n_cols)] q_tbl.add_row(row, mapper=bold, color="cream") row = [gen_example(n + i*n_cols, n_digits, n_nums, digit_var) for n in range(0, n_cols)] q_tbl.add_row([r[0] for r in row]) if i % 2 == 0: #a_tbl.add_row([r[1] for r in row], color = 'lightgray') a_tbl.add_row([r[1] for r in row], color = 'cream') else: a_tbl.add_row([r[1] for r in row]) # write the file q_doc.generate_pdf(out_dir + '/' + f_nm + str(n_digits) + '_digits_Q', clean_tex=False) a_doc.generate_pdf(out_dir + '/' + f_nm + str(n_digits) + '_digits_A', clean_tex=False) print("----- DONE -----")
def fill_document(doc): """Add a section, a subsection and some text to the document. :param doc: the document :type doc: :class:`pylatex.document.Document` instance """ with doc.create(Section('A section')): doc.append('Some regular text and some ') doc.append(italic('italic text. ')) with doc.create(Subsection('A subsection')): doc.append('Also some crazy characters: $&#{}')
def insert_question(self, doc): with doc.create(Section(str(self))): # Generate the LaTeX code to insert each question of this topic into the document. doc.append(self.leading_text()) doc.append(NoEscape(r'\begin{multicols}{%i}' % self.n_cols)) doc.append(NoEscape(r'\begin{enumerate}[label=(\alph*)]')) for i in range(0, len(self.fcns)): doc.append(NoEscape(r'\item \[%s \]' % latex(self.fcns[i]))) doc.append(NoEscape(r'\end{enumerate}')) doc.append(NoEscape(r'\end{multicols}')) return doc
def preamble(self): geometry_options = {"margin": "0.5cm", "includeheadfoot": True} doc = Document(page_numbers=True, geometry_options=geometry_options) doc.preamble.append(NoEscape(r'\usepackage[czech]{babel}')) doc.documentclass.options = Options('10pt') with doc.create(Section('Zhodnocení požární odolnosti konstrukcí')): doc.append( NoEscape( r'Normový požadavek na požární odolnost konstrukcí je stanoven na základě stupně požární bezpečnosti jednotlivých požárních úseků (viz tabulka \ref{PU}), a to pomocí tabulky 12 v normě ČSN 73 0802.' )) return doc
def _document_fe_graph(self) -> None: """Add FE execution graphs into the traceability document. """ with self.doc.create(Section("FastEstimator Architecture")): for mode in self.system.pipeline.data.keys(): scheduled_items = self.system.pipeline.get_scheduled_items( mode) + self.system.network.get_scheduled_items( mode) + self.system.traces signature_epochs = get_signature_epochs( scheduled_items, total_epochs=self.system.epoch_idx, mode=mode) epochs_with_data = self.system.pipeline.get_epochs_with_data( total_epochs=self.system.epoch_idx, mode=mode) if set(signature_epochs) & epochs_with_data: self.doc.append(NoEscape(r'\FloatBarrier')) with self.doc.create(Subsection(mode.capitalize())): for epoch in signature_epochs: if epoch not in epochs_with_data: continue self.doc.append(NoEscape(r'\FloatBarrier')) with self.doc.create( Subsubsection( f"Epoch {epoch}", label=Label( Marker(name=f"{mode}{epoch}", prefix="ssubsec")))): ds_ids = self.system.pipeline.get_ds_ids( epoch=epoch, mode=mode) for ds_id in ds_ids: with NonContext( ) if ds_id == '' else self.doc.create( Paragraph( f"Dataset {ds_id}", label=Label( Marker( name= f"{mode}{epoch}{ds_id}", prefix="para")))): diagram = self._draw_diagram( mode, epoch, ds_id) ltx = d2t.dot2tex(diagram.to_string(), figonly=True) args = Arguments( **{ 'max width': r'\textwidth, max height=0.9\textheight' }) args.escape = False with self.doc.create(Center()): with self.doc.create( AdjustBox(arguments=args) ) as box: box.append(NoEscape(ltx))
def fill_document(doc): with doc.create(Section('A section')): doc.append('Some regular text and some ') doc.append(italic('italic text. ')) doc.append(bold('bold text. ')) with doc.create(Subsection('A subsection')): doc.append('Also some crazy characters: $&#{}') doc.append( NoEscape( r"$$f'(a) = \lim_{x \to a} \frac{f(x) - f(a)}{x-a}$$"))
def append_center(self): with self.gen.doc.create(Section(self.gen.tpdf.center_solving)): with self.gen.doc.create(Subsection(self.gen.tpdf.center_formula)): self.gen.pdf.add_equation(self.gen.tpdf.center + r' = \frac{\sigma_x + \sigma_y}{2}') with self.gen.doc.create(Subsection(self.gen.tpdf.center_solving)): self.gen.pdf.add_equation( self.gen.tpdf.center + r' = \frac{' + f'{self.res.sigma_x} +' + f'{self.res.sigma_y}' + '}{2}') self.gen.pdf.add_equation( f'{self.gen.tpdf.center} = {append_result((self.res.sigma_x + self.res.sigma_y) / 2)}' )
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
def _document_training_graphs(self) -> None: """Add training graphs to the traceability document. """ with self.doc.create(Section("Training Graphs")): log_path = os.path.join(self.figure_dir, f'{self.report_name}_logs.png') visualize_logs(experiments=[self.system.summary], save_path=log_path, verbose=False, ignore_metrics={'num_device', 'logging_interval'}) with self.doc.create(Figure(position='h!')) as plot: plot.add_image(os.path.relpath(log_path, start=self.save_dir), width=NoEscape(r'1.0\textwidth,height=0.95\textheight,keepaspectratio'))
#!/usr/bin/env python from pylatex import Document, Section from pylatex.utils import escape_latex doc = Document(default_filename="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) ''') section.append(text) doc.append(section) doc.generate_pdf()
#!/usr/bin/python3 import numpy as np from pylatex import Document, Section, Subsection, Table, Math from pylatex.numpy import Matrix, format_vec a = np.array([[100, 10, 20]]).T doc = Document() section = Section('Numpy tests') subsection = Subsection('Array') vec = Matrix(a) vec_name = format_vec('a') math = Math(data=[vec_name, '=', vec]) subsection.append(math) section.append(subsection) subsection = Subsection('Matrix') M = np.matrix([[2, 3, 4], [0, 0, 1], [0, 0, 2]]) matrix = Matrix(M, mtype='b') math = Math(data=['M=', matrix]) subsection.append(math) section.append(subsection)
#!/usr/bin/python from pylatex import ( Document, Section, Subsection, Table, MultiColumn, MultiRow ) doc = Document("multirow") section = Section('Multirow Test') test1 = Subsection('MultiColumn') test2 = Subsection('MultiRow') test3 = Subsection('MultiColumn and MultiRow') test4 = Subsection('Vext01') table1 = Table('|c|c|c|c|') table1.add_hline() table1.add_row((MultiColumn(4, '|c|', 'Multicolumn'),)) table1.add_hline() table1.add_row((1, 2, 3, 4)) table1.add_hline() table1.add_row((5, 6, 7, 8)) table1.add_hline() row_cells = ('9', MultiColumn(3, '|c|', 'Multicolumn not on left')) table1.add_row(row_cells) table1.add_hline()
#!/usr/bin/python3 import numpy as np from pylatex import Document, Section, Subsection, Table, Math from pylatex.numpy import Matrix from pylatex.utils import italic doc = Document() section = Section('Yaay the first section, it can even be ' + italic('italic')) section.append('Some regular text') math = Subsection('Math', data=[Math(data=['2*3', '=', 6])]) section.append(math) table = Table('rc|cl') table.add_hline() table.add_row((1, 2, 3, 4)) table.add_hline(1, 2) table.add_empty_row() table.add_row((4, 5, 6, 7)) table = Subsection('Table of something', data=[table]) section.append(table) a = np.array([[100, 10, 20]]).T M = np.matrix([[2, 3, 4], [0, 0, 1], [0, 0, 2]])
from pylatex import Document, Section, Subsection from pylatex.command import Command doc = Document() sub_sec1 = 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()
# Then start the document doc = Document() doc.preamble.append(Command('title', 'Benchmark analysis of %d problems and %d configurations.' % (len(fnames), len(options)))) doc.preamble.append(Command('author', "Charles Prud'homme")) doc.append(NoEscape(r'\maketitle')) doc.packages.append(Package('geometry')) presec = "" prevsubsec = "" section = None subsection = None if args.plot: # First global view section = Section('Global') doc.append(section) with doc.create(TikZ()): with doc.create(Axis(options='xlabel=Instances (ordered wrt to increasing resolution time),' 'ylabel=CPU time (s),height=20cm, width=15cm,legend pos=outer north east')) as plot: for opt in options: times = timPerOpt[opt] times.sort() coords = [] for i in range(0, len(times)): coords.append((i, times[i])) plot.append(Plot(name=opt, coordinates=coords)) if args.plot: # First global view
#!/usr/bin/env python from pylatex import Document, Section from pylatex.graphics import Figure doc = Document() section = Section("Multirow Test") figure = Figure() figure.add_image("docs/static/screenshot.png") figure.add_caption("Whoooo an imagage of a pdf") section.append(figure) doc.append(section) doc.generate_pdf()
#table.add_hline() #for _ in range(1, len(result)): # table.add_row(result[_]) #table = Subsection('Table', data=[table]) # #section.append(table) #doc.append(section) #doc.generate_tex() result_ms = get_coordinates("master-slave") result_drbd = get_coordinates("drbd") result_galera = get_coordinates("galera") doc = Document() section = Section('yay') tikz = TikZ() axis = Axis(options='height=6cm, width=6cm, grid=major') plot1 = Plot(name='read', coordinates=result_ms[2]) plot2 = Plot(name='write', coordinates=result_drbd[2]) plot3 = Plot(name='read-write', coordinates=result_galera[2]) axis.append(plot1) axis.append(plot2) axis.append(plot3) tikz.append(axis) plot_section = Subsection('Random graph', data=[tikz])
__FILENAME__ = example #!/usr/bin/python import numpy as np from pylatex import Document, Section, Subsection, Table, Math, TikZ, Axis, \ Plot from pylatex.numpy import Matrix from pylatex.utils import italic doc = Document() section = Section('Yaay the first section, it can even be ' + italic('italic')) section.append('Some regular text') math = Subsection('Math that is incorrect', data=[Math(data=['2*3', '=', 9])]) section.append(math) table = Table('rc|cl') table.add_hline() table.add_row((1, 2, 3, 4)) table.add_hline(1, 2) table.add_empty_row() table.add_row((4, 5, 6, 7)) table = Subsection('Table of something', data=[table]) section.append(table) a = np.array([[100, 10, 20]]).T M = np.matrix([[2, 3, 4],
__author__ = 'Michael' from final_ode_8_com_plot_2 import Respostas from pylatex import Document,Section,Subsection,Table,Math,Plot doc = Document() section = Section("Este e o primeiro relatorio em PDF para eqs diferenciais v01:") section.append("Importante notar que essa bagaca esta em fase de testes, pode bugar tudo") doc.append(section) doc.generate_pdf()
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) # SectionBase s = Section(title='', numbering=True, data=None) # Math m = Math(data=None, inline=False) # Tabular t = Tabular(table_spec='|c|c|', data=None, pos=None) t.add_hline(start=None, end=None) t.add_row(cells=(1, 2), escape=False) t.add_multicolumn(size=2, align='|c|', content='Multicol', cells=None, escape=False)