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()
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
def construct_pdf(email_addr): """ Takes the list of email addresses as input and makes sure that an API call to Haveibeenpwnd is being made for each email address. Afterwards it creates a LaTeX document with a section for each email address that was used as input. If the API call doesnt return anything, a standard output text is produced in the LaTeX document. This function also calls the function to create tables. Currently I hardcoded the amount of breaches that are contained within one table to be 3. Finally the function created a PDF file from the LaTeX document in the same directory if this script. """ pdf = Document() pdf.preamble.append(Command('title', 'Overview of breached accounts')) pdf.preamble.append(Command('author', 'Python')) pdf.preamble.append(Command('date', NoEscape(r'\today'))) pdf.append(NoEscape(r'\maketitle')) with pdf.create(Section("Introduction")) as intro_section: intro_section.append( "This PDF document lists breaches for websites you were registered on. " ) intro_section.append( " Please note that with each breach the leaked PII is also shown.") for email_entry in email_addr: with pdf.create(Section("Email address: " + email_entry)) as email_section: data = check_pwn(email_entry) start_entry = 0 stop_entry = 3 counter = 0 if data == None: email_section.append( "The API didn't return anything usable, so probably you're all good!" ) elif stop_entry == len(data): create_tables(data, email_section, start_entry, stop_entry, counter) else: while stop_entry <= (len(data) - 1): create_tables(data, email_section, start_entry, stop_entry, counter) counter = counter + 3 start_entry = start_entry + 2 stop_entry = start_entry + 3 pdf.generate_pdf("breached")
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)
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)
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')
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)
def generate_user_stories(schema: PLDSchema, locale: LocaleDictionary, document: Document) -> Document: document.append(NewPage()) with document.create(Section(title=locale.user_stories)) as section: section: Section for deliverable in schema.deliverables: with section.create( Subsection(title=deliverable.name)) as subsection: subsection: Subsection if deliverable.description is not None: subsection.append(MediumText(data=deliverable.description)) for subset in deliverable.subsets: with subsection.create( Subsubsection(title=subset.name)) as subsubsection: subsubsection: Subsubsection if subset.description is not None: subsubsection.append( MediumText(data=subset.description)) for user_story in subset.user_stories: with subsubsection.create( Paragraph( title=user_story.name)) as paragraph: paragraph: Paragraph paragraph.append(Command("mbox", "")) paragraph.append(NoEscape("\\\\\n")) generate_user_story(user_story, locale, paragraph) return document
def _build_drawing(self): doc = Document() with doc.create(TikZ()) as tikz_pic: # create a node node_options = { 'align': 'center', 'inner sep': '20pt', 'label': '{{270:{}}}'.format(self.module.name) } box = TikZNode(handle='module', options=TikZOptions('draw', 'rounded corners', **node_options)) tikz_pic.append(box) for port in self.module.ports: if port.direction == 'in': tikz_pic.append( TikZNode(text=port.name, options=TikZOptions(anchor='west'), at=TikZCoordinate(-1, 1))) break doc.generate_tex('test') return doc
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)
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)
def test_three(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() fig.add_caption("full") doc.generate_tex("Latex/threesubfigures")
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()
def add_shopping_list(doc: Document, camp: Camp): # content for this page doc.append(Section('Einkaufsliste', numbering=False)) # space between colums doc.append(Command('setlength')) doc.append(Command('columnsep', arguments='40pt')) doc.packages.add(Package('multicol')) doc.packages.add(Package('enumitem')) doc.packages.add(Package('setspace')) for _ in range(1): doc.append(Subsubsection('Gemüse und Früchte', numbering=False)) with doc.create(Multicols(arguments='2')) as multicols: multicols.append(Command('small')) with multicols.create( Description( options='leftmargin=1.75cm, itemsep=4pt')) as itemize: # space between colums itemize.append( Command('setlength', arguments=Command('itemsep'), extra_arguments='0pt')) itemize.append( Command('setlength', arguments=Command('parskip'), extra_arguments='0pt')) itemize.add_item('100g', 'the first item') itemize.add_item('23 Stk.', 'Bananen') itemize.add_item('100g', 'the first item') itemize.add_item('10g', 'the item')
def generate_first_page(schema: PLDSchema, document: Document) -> Document: document.append(LargeText(Command("maketitle"))) document.append(VerticalSpace("4cm")) with document.create(Center()) as center: center: Center center.append(LargeText(bold(schema.subtitle))) return document
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)
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 create_pdf_document(fullnames, emails): doc = Document() doc.preamble.append(Command("title", "My employees")) doc.preamble.append(Command("author", "Rishikesh Agrawani")) doc.preamble.append(Command("date", NoEscape(r'\today'))) doc.append(NoEscape(r"\maketitle") ) # Very important line, if not added(details won't be added) 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("users-details-maketile-activated", clean_tex=False)
def generate_pdf(driver, url, fname_base): license_url = '%s/blob/master/LICENSE' % url license_txt = get_license(driver, license_url) doc = Document(geometry_options=LATEX_OPTION) doc.preamble.append(Command('title', fname_base)) doc.append(NoEscape('\\maketitle')) with doc.create(Section('LICENSE')): doc.append(license_txt) with doc.create(Section('Web pages')): for fname_rule in FNAME_RULE: fname = fname_rule % (IMAGEPATH, fname_base) with doc.create(Figure(position='!htbp')) as fig: fig.add_image(fname, width=NoEscape('\\textwidth')) doc.generate_pdf('pdfs/%s' % fname_base, clean_tex=False, compiler='pdflatex')
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
def generatePdf(articles): geometryOptions = {"tmargin": "1cm", "lmargin": "10cm"} doc = Document(geometry_options=geometryOptions) for article in articles: with doc.create(Section(article["title"])): doc.append(article["description"]) doc.append(article["url"]) doc.generate_pdf("newsArticles")
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 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)
class LatexManager(): def __init__(self, doc_file_name): from pylatex import Document self.doc_file_name = doc_file_name geometry_options = {"tmargin": "1cm", "lmargin": "1cm"} self.doc = Document(geometry_options=geometry_options) def add_image(self, image_filename, title_name): from pylatex import Subsection, Figure with self.doc.create(Subsection(title_name)): with self.doc.create(Figure(position='h!')) as kitten_pic: kitten_pic.add_image(image_filename, width='360px') kitten_pic.add_caption('image_description') def __del__(self): self.doc.generate_pdf(self.doc_file_name, clean_tex=True)
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 = [ "aduiashdDASDASDASDSADSAuiasuidhasuidhasi", "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)
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
def generate_report(tests, program, is_loopback, calib_program, dut_host): geometry_options = {"right": "2cm", "left": "2cm"} fname = program.split('/')[-1] + '-tests' try: os.remove(fname + '.pdf') except OSError: pass doc = Document(fname, geometry_options=geometry_options) doc.append('Test results for %s\n' % program) doc.append('Calibration method: %s\n' % "loopback" if is_loopback else calib_program) doc.append('DUT host: %s\n' % dut_host) sorted_tests = sorted(tests, key = lambda test: len(test.expected_path)) for i in range(len(sorted_tests)): times = sorted(tests[i].packets[0].times) runs = range(len(times)) plt.figure(figsize=(16,5)) plt.bar(runs, times) plt.xlim(runs[0], runs[-1] + 1) plt.xlabel('Run #') plt.ylabel('Time - calibration (microseconds) ') plt.title('Test times') with doc.create(Section('Test %d' % (i+1))): with doc.create(Subsection('Expected path')): for point in tests[i].expected_path: if 'tbl_act' in point: continue doc.append(str(point) + '\n') with doc.create(Subsection('Stats (time - calibration time in microseconds)')): doc.append('Mean: %f\n' % np.mean(times)) doc.append('Std dev: %f\n' % np.std(times)) doc.append('Median: %f\n' % np.median(times)) with doc.create(Figure(position='htbp')) as plot: plot.add_plot(width=NoEscape(r'1\textwidth')) plt.clf() plt.close() gc.collect() doc.generate_pdf(clean_tex=True)
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')
class ExperimentWriter(object): def __init__(self, sv_file): self._sv_file = sv_file geo_opts = {'tmargin': '1cm', 'lmargin': '10com'} self._doc = Document() # self._doc.create(Section('Examples')) def add_result(self, image_id, quest_id, im_path, answer, questions): with self._doc.create(Section('quest_id: %d' % quest_id)): # add figure with self._doc.create(Figure(position='h!')) as fig: fig.add_image(im_path, width='%dpx' % _compute_width(im_path)) fig.add_caption('Image: %d' % image_id) # add answer with self._doc.create(Subsection('%s' % answer)): if len(questions) % 2 == 1: questions.append('') with self._doc.create(Tabular(table_spec='|l|l|')) as table: num = int(len(questions) * 0.5) table.add_hline() for i in range(num): a = '%s' % questions[2 * i].capitalize() a = textwrap.fill(a, width=45).split('\n') len_a = len(a) b = '%s' % questions[2 * i + 1].capitalize() b = textwrap.fill(b, width=45).split('\n') len_b = len(b) max_len = max(len_a, len_b) a += [''] * (max_len - len_a) b += [''] * (max_len - len_b) for a_i, b_i in zip(a, b): table.add_row((a_i, b_i)) table.add_hline() # table.add_hline() # questions # for q in questions: # self._doc.append('\n%s' % q.capitalize()) # with self._doc.create(Itemize()) as item: # for q in questions: # item.add_item(q.capitalize()) self._doc.append(NewPage()) def render(self): self._doc.generate_pdf(self._sv_file, clean=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 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)
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 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()
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 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)
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
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)
def createSimpleTable(tableColumns,d,filename): doc = Document() with doc.create(Table('|c|c|c|c|c|c|c|c|c|')) as table: for row in d: row[0]=row[0].replace('_','\_') row[0]="\\textbf{"+row[0]+"}" table.add_hline() table.add_row(tuple(row)) table.add_hline() a = open(filename, 'wr') table.dump(a)
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"])
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)
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)
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 Ascenso(objective, varbls, f, punto): l = Symbol("r") s = Symbol("x") varbls = [ Symbol(var) for var in varbls if var in f ] f = Lambda(varbls, f) Nabla = [ Lambda(varbls, diff(f(*flatten(varbls)),var)) for var in varbls ] punto = Matrix(punto) count = 1 nabla_eval = Matrix([ Nab(*flatten(punto)) for Nab in Nabla ]) out = open("../data/data.out", "w") ### Para crear el .pdf con latex doc = Document() doc.packages.append(Package('geometry', options=['margin=1in'])) doc.packages.append(Package('inputenc', options=['utf8'])) doc.packages.append(Package('babel', options=['spanish', 'activeacute'])) doc.packages.append(Package('enumerate')) doc.packages.append(Package('amsthm')) doc.packages.append(Package('amssymb')) doc.packages.append(Package('amsmath')) doc.append('\\decimalpoint') doc.append('Maximizar:' if objective else 'Minimizar:') doc.append(Math(data = ['f('+ parseVarbls(varbls) + ')=' + parseFunction(f, varbls)] )) doc.append('Derivando la función:') doc.append('\\begin{align*}') for i in range(len(Nabla)): out.write('D_' + str(varbls[i]) + " = " + str(Nabla[i](*flatten(varbls))).replace('**', '^') + '\n' ) doc.append('\\nabla f_{' + str(varbls[i]) + "} & = " + parseFunction(Nabla[i], varbls) + '\\\\' ) doc.append('\\end{align*}') doc.append('Tomamos como punto inicial $p_0 =('+parseVarbls(list(punto))+')$.\ Iterando con el método del \\textit{ascenso/descenso más pronunciado} obtenemos:$$$$') condition = conditional(nabla_eval) while(condition > 0): ### latex doc.append('\\textbf{Iteración '+str(count)+'.}\\\\') doc.append('Evaluamos $\\nabla f$ en el punto $p_{'+str(count-1)+'}=(' + parseVarbls([round(c, 3) for c in punto]) + \ ')$, entonces $\\nabla f =(' + parseVarbls([round(c, 3) for c in nabla_eval]) + ')$. Obteniendo $h(r)$:') h = Lambda(l, f(*flatten(punto + l*nabla_eval))) l_nopt = findOptimum(h, objective) punto = punto + l_nopt*nabla_eval ### salida out.write("\nIteración " + str(count)+'\\\\') out.write("\n\nNabla(p_" + str(count - 1) + ") = " + str(list(nabla_eval)) + "\n") out.write(("\nMAX " if objective == 1 else "\nMIN ") + "h(r)=" + str(h(l)).replace('**', '^')) out.write("\nlamb = " + str(l_nopt) + "\n") out.write('\np_' + str(count) + ' = ' + str(list(punto)) + '\n') ### latex doc.append(Math(data=['h(r)='+parseFunction(h, [l])])) doc.append(('Maximizando' if objective else 'Minimizando')+' $h$ encontramos $r$='+str(round(l_nopt, 3))+'.\ Asà $p_{'+str(count)+'}$=('+parseVarbls([round(c, 3) for c in punto])+').$$$$') doc.append('\\begin{center}') with doc.create(TikZ()): plot_options = 'height=9cm, width=9cm, xmin=' + str(l_nopt-5) with doc.create(Axis(options=plot_options)) as plot: plot_options = 'smooth, red' functoplot = str(h(s).expand()).replace('**', '^') plot.append(Plot(name='h(r)', func=functoplot, options=plot_options)) plot.append(Plot(name='(h(r),r)', coordinates=[[N(l_nopt), N(h(l_nopt))]])) doc.append('\\end{center}') doc.append('$$$$') nabla_eval = Matrix([ N(Nab(*flatten(punto))) for Nab in Nabla ]) condition = conditional(nabla_eval) count = count + 1 ### latex doc.append('Por lo tanto el punto '+('máximo' if objective else 'mÃnimo')+' es: ('+parseVarbls([round(c, 3) for c in punto])+')') doc.generate_pdf('ascenso') os.system('mv ascenso.pdf ../pdfs/ascenso.pdf') os.system('okular ../pdfs/ascenso.pdf &') out.close()
# begin-doc-include import numpy as np from pylatex import Document, Section, Subsection, Tabular, Math, TikZ, Axis, \ Plot, Figure, Package, Matrix from pylatex.utils import italic import os if __name__ == '__main__': image_filename = os.path.join(os.path.dirname(__file__), 'kitten.jpg') doc = Document() doc.packages.append(Package('geometry', options=['tmargin=1cm', 'lmargin=10cm'])) with doc.create(Section('The simple stuff')): doc.append('Some regular text and some') doc.append(italic('italic text. ')) doc.append('\nAlso some crazy characters: $&#{}') with doc.create(Subsection('Math that is incorrect')): doc.append(Math(data=['2*3', '=', 9])) with doc.create(Subsection('Table of something')): with doc.create(Tabular('rc|cl')) as table: 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)) a = np.array([[100, 10, 20]]).T
#Table header table_format = 'llllllll' #Elements we want to put in the table idces_table = (dz.reducDf.frame_tag.isin(dz.observation_dict['objects'] + dz.observation_dict['Standard_stars'] + ['flat', 'arc'])) & (dz.reducDf.file_location.str.contains('/raw_fits/')) file_names = dz.reducDf[idces_table].sort_values(['RUN']).file_name.values file_folders = dz.reducDf[idces_table].sort_values(['RUN']).file_location.values RA_values = dz.reducDf[idces_table].sort_values(['RUN']).RA.values DEC_values = dz.reducDf[idces_table].sort_values(['RUN']).DEC.values UT = dz.reducDf[idces_table].sort_values(['RUN']).UT.values objects = dz.reducDf[idces_table].sort_values(['RUN']).frame_tag.values color = dz.reducDf[idces_table].sort_values(['RUN']).ISIARM.values valid_values = dz.reducDf[idces_table].sort_values(['RUN']).valid_file.values #Fill the table with doc.create(Tabular(table_format)) as table: #Adding the header headers = ['Object', 'Frame', 'Arm', 'UT', 'RA', 'DEC', 'Flat Blue', 'Flat Red'] row_values = [None] * len(headers) table.add_row(headers, escape=False) table.add_hline() for i in range(len(file_names)): #Get the righ match if it is a target if objects[i] in (dz.observation_dict['Standard_stars'] + dz.observation_dict['objects']): blue_object = matched_frames['{codename}_{arm_color}_{calib_file}_bySeparation'.format(codename = objects[i], arm_color = 'Blue', calib_file = 'flat')] red_object = matched_frames['{codename}_{arm_color}_{calib_file}_bySeparation'.format(codename = objects[i], arm_color = 'Red', calib_file = 'flat')] match = [blue_object, red_object]
#!/usr/bin/python from pylatex import Document, Section, Subsection, Table 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(Table('|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(Table('|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()
def create_reading_section(document, medium): with document.create(Subsection('Reading')): with document.create(Itemize()) as itemize: try: df = pd.read_csv(os.path.join(medium, 'reading.csv')) except pd.errors.EmptyDataError: return for _, row in df.iterrows(): title = row.Title link = row.Link itemize.add_item(italic(title)) itemize.append(NewLine()) arguments = Arguments(link, link) itemize.append(Command('href', arguments=arguments)) for medium in ['books', 'papers']: with document.create(Section(medium.capitalize())): if medium == 'books': create_read_section(document, medium) create_reading_section(document, medium) elif medium == 'papers': create_read_section(document, medium) document.generate_tex('read') document.generate_pdf('read', compiler='pdflatex', clean_tex=False)
from pylatex.base_classes import Environment from pylatex.package import Package from pylatex import Document, Section from pylatex.utils import NoEscape class AllTT(Environment): """A class to wrap LaTeX's alltt environment.""" packages = [Package('alltt')] escape = False content_separator = "\n" # Create a new document doc = Document() with doc.create(Section('Wrapping Latex Environments')): doc.append(NoEscape( r""" The following is a demonstration of a custom \LaTeX{} command with a couple of parameters. """)) # Put some data inside the AllTT environment with doc.create(AllTT()): verbatim = ("This is verbatim, alltt, text.\n\n\n" "Setting \\underline{escape} to \\underline{False} " "ensures that text in the environment is not\n" "subject to escaping...\n\n\n" "Setting \\underline{content_separator} " "ensures that line endings are broken in\n" "the latex just as they are in the input text.\n"
class ExampleCommand(CommandBase): """ A class representing a custom LaTeX command. This class represents a custom LaTeX command named ``exampleCommand``. """ _latex_name = 'exampleCommand' packages = [Package('color')] # Create a new document doc = Document() with doc.create(Section('Custom commands')): doc.append(NoEscape( r""" The following is a demonstration of a custom \LaTeX{} command with a couple of parameters. """)) # Define the new command new_comm = Command('newcommand', '\exampleCommand', options=3, extra_arguments=r'\color{#1} #2 #3 \color{black}') doc.append(new_comm) # Use our newly created command with different arguments doc.append(ExampleCommand(arguments=Arguments('blue', 'Hello', 'World!'))) doc.append(ExampleCommand(arguments=Arguments('green', 'Hello', 'World!'))) doc.append(ExampleCommand(arguments=Arguments('red', 'Hello', 'World!')))
with doc.create(Subsection("A subsection")): doc.append("Also some crazy characters: $&#{}") if __name__ == "__main__": # Basic document doc = Document("basic") fill_document(doc) doc.generate_pdf() doc.generate_tex() # Document with `\maketitle` command activated doc = Document() doc.preamble.append(Command("title", "Awesome Title")) doc.preamble.append(Command("author", "Anonymous author")) doc.preamble.append(Command("date", NoEscape(r"\today"))) doc.append(NoEscape(r"\maketitle")) fill_document(doc) doc.generate_pdf("basic_maketitle", clean=False) # Add stuff to the document with doc.create(Section("A second section")): doc.append("Some text.") doc.generate_pdf("basic_maketitle2") tex = doc.dumps() # The document as string in LaTeX syntax
HII_Galaxy_List = Data_Dict.keys() HII_Galaxy_List.sort() #Generate Document doc = Document(Table_Folder+ Table_Name) doc.packages.append(Package('geometry', options=['tmargin=2cm', 'lmargin=1cm', 'rmargin=1cm','bmargin=2cm'])) doc.packages.append(Package('floatrow')) doc.preamble.append(r'\DeclareFloatFont{huge}{\huge}') doc.preamble.append(r'\floatsetup[table]{font=huge}') # doc.append(r'\DeclareFloatFont{tiny}{\tiny}') # doc.append(r'\floatsetup[table]{font=tiny}') #Main section manuscript with doc.create(Section('HII Galaxies properties:')): for i in range(len(HII_Galaxy_List)): Galaxy = HII_Galaxy_List[i] with doc.create(Subsection('Galaxy ' + Galaxy)): with doc.create(Table('|c|c|')) as table: for parameter in parameter_List: Label = Properties_dict[parameter]['label'] value = str(Data_Dict[Galaxy][parameter]) table.add_hline() table.add_row((Label, value)) doc.append(r'\newpage') doc.append(r'\tiny')
from pylatex import Document, Section, Figure, SubFigure doc = Document(default_filepath='subfigures') with doc.create(Section('Showing subfigures')): with doc.create(Figure(position='h!')) as kittens: with doc.create(SubFigure(position='b', width=r'0.45\linewidth')) as left_kitten: left_kitten.add_image('docs/static/kitten.jpg', width=r'\linewidth') left_kitten.add_caption('Kitten on the left') with doc.create(SubFigure(position='b', width=r'0.45\linewidth')) as right_kitten: right_kitten.add_image('docs/static/kitten.jpg', width=r'\linewidth') right_kitten.add_caption('Kitten on the right') kittens.add_caption("Two kittens") doc.generate_pdf()
#!/usr/bin/python from pylatex import Document, Section, Subsection, Table doc = Document(filename="multirow") with doc.create(Section('Multirow Test')): with doc.create(Subsection('Multicol')): with doc.create(Table('|c|c|')) as table1: # we need to keep track of the object here 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(Table('|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()
def createFullTable(tableColumns,d_challange,d_pool,d_weighted,filename): doc = Document() order=[x[0] for x in d_challange]; # delete unnecessary data deleteColumns(d_challange,4,6) deleteColumns(d_pool,1,6) #deleteColumns(d_weighted,5,7) d_challange=colorTopResults(d_challange) d_pool= colorTopResults(d_pool) #d_weighted=colorTopResults(d_weighted) print d_challange print d_pool # find top 3 in each column replace 1 with red color, 2 with blue, 3 with red. If there is tie same color # should be used addBoldLate=lambda x: "\\textbf{" + x + "}" with doc.create(Table('|c|c|c|c|c|c|c|c|c|c|')) as table: topLine = list() table.add_hline() topLine.append("Experiment ") topLine.append("\multicolumn{3}{ | c |}{Baseline} ") topLine.append("\multicolumn{3}{ | c |}{Region pertubation} ") topLine.append("\multicolumn{3}{ | c |}{Averaged} ") table.add_row(topLine) normalizationLine=list() table.add_hline() normalizationLine.append("Normalization ") normalizationLine.append("\multicolumn{3}{ | c |}{sequence - pooled} ") normalizationLine.append("\multicolumn{3}{ | c |}{sequence - pooled} ") normalizationLine.append("\multicolumn{3}{ | c |}{per - attribute} ") table.add_row(normalizationLine) # \hline # Normalization & \multicolumn # {3} # { | c |}{sequence - pooled} & \multicolumn # {3} # { | c |}{sequence - pooled} & \multicolumn # {3} # { | c |}{per - attribute} \ \ # \hline table.add_hline() header3=list() header3.append('Ranking measure') for i in range(0,3): header3.append('A') header3.append('R') header3.append('Avg.') table.add_row(header3) table.add_hline() table.add_hline() for tracker in order: line1=[x for x in d_challange if x[0]==tracker][0] line2 = [x for x in d_pool if x[0] == tracker][0] tracker = tracker.replace('_', '\_') trackerName = tracker #table.add_hline() row=list() row.append(trackerName) row=row+line2[1:] + line1[1:] # find line corresponding table.add_row(row) table.add_hline() #print table a = open(filename, 'wr') table.dump(a)
def generate_unique(): geometry_options = { "head": "40pt", "margin": "0.5in", "bottom": "0.6in", "includeheadfoot": True } doc = Document(geometry_options=geometry_options) # Generating first page style first_page = PageStyle("firstpage") # Header image with first_page.create(Head("L")) as header_left: with header_left.create(MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c')) as logo_wrapper: logo_file = os.path.join(os.path.dirname(__file__), 'sample-logo.png') logo_wrapper.append(StandAloneGraphic(image_options="width=120px", filename=logo_file)) # Add document title with first_page.create(Head("R")) as right_header: with right_header.create(MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c', align='r')) as title_wrapper: title_wrapper.append(LargeText(bold("Bank Account Statement"))) title_wrapper.append(LineBreak()) title_wrapper.append(MediumText(bold("Date"))) # Add footer with first_page.create(Foot("C")) as footer: message = "Important message please read" with footer.create(Tabularx( "X X X X", arguments=NoEscape(r"\textwidth"))) as footer_table: footer_table.add_row( [MultiColumn(4, align='l', data=TextColor("blue", message))]) footer_table.add_hline(color="blue") footer_table.add_empty_row() branch_address = MiniPage( width=NoEscape(r"0.25\textwidth"), pos='t') branch_address.append("960 - 22nd street east") branch_address.append("\n") branch_address.append("Saskatoon, SK") document_details = MiniPage(width=NoEscape(r"0.25\textwidth"), pos='t', align='r') document_details.append("1000") document_details.append(LineBreak()) document_details.append(simple_page_number()) footer_table.add_row([branch_address, branch_address, branch_address, document_details]) doc.preamble.append(first_page) # End first page style # Add customer information with doc.create(Tabu("X[l] X[r]")) as first_page_table: customer = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h') customer.append("Verna Volcano") customer.append("\n") customer.append("For some Person") customer.append("\n") customer.append("Address1") customer.append("\n") customer.append("Address2") customer.append("\n") customer.append("Address3") # Add branch information branch = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='t!', align='r') branch.append("Branch no.") branch.append(LineBreak()) branch.append(bold("1181...")) branch.append(LineBreak()) branch.append(bold("TIB Cheque")) first_page_table.add_row([customer, branch]) first_page_table.add_empty_row() doc.change_document_style("firstpage") doc.add_color(name="lightgray", model="gray", description="0.80") # Add statement table with doc.create(LongTabu("X[l] X[2l] X[r] X[r] X[r]", row_height=1.5)) as data_table: data_table.add_row(["date", "description", "debits($)", "credits($)", "balance($)"], mapper=bold, color="lightgray") data_table.add_empty_row() data_table.add_hline() row = ["2016-JUN-01", "Test", "$100", "$1000", "-$900"] for i in range(30): if (i % 2) == 0: data_table.add_row(row, color="lightgray") else: data_table.add_row(row) doc.append(NewPage()) # Add cheque images with doc.create(LongTabu("X[c] X[c]")) as cheque_table: cheque_file = os.path.join(os.path.dirname(__file__), 'chequeexample.png') cheque = StandAloneGraphic(cheque_file, image_options="width=200px") for i in range(0, 20): cheque_table.add_row([cheque, cheque]) doc.generate_pdf("complex_report", clean_tex=False)
# -*- coding: utf-8 -*- import numpy from pylatex import Document, Section, Subsection, Tabular, Math, TikZ, Axis, Plot, Figure, Package, Matrix from pylatex.utils import italic import os import re import math if __name__ == "__main__": identifiers = ["eval7_concat_noopt", "eval7_concat_opt"] doc = Document() doc.packages.append(Package("geometry", options = ["tmargin=1cm", "lmargin=1cm"])) with doc.create(Section("Stuff")): coordinates = {} for identifier in identifiers: print("Preparing {}".format(identifier)) coordinates[identifier] = [] data = [] with open("../logs/{}_comp.log".format(identifier)) as f: for line in f: m = re.match(r"^INFO: Compilation took (.+?) s$", line) if m is not None: (a,) = m.groups() a = float(a) data.append(a) # data = data[0:24] limits = [1, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000] for i in range(int(len(data) / 4)):
#!/usr/bin/python """ This example shows subfigure functionality. .. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ # begin-doc-include from pylatex import Document, Section, Figure, SubFigure, NoEscape import os if __name__ == "__main__": doc = Document(default_filepath="subfigures") image_filename = os.path.join(os.path.dirname(__file__), "kitten.jpg") with doc.create(Section("Showing subfigures")): with doc.create(Figure(position="h!")) as kittens: with doc.create(SubFigure(position="b", width=NoEscape(r"0.45\linewidth"))) as left_kitten: left_kitten.add_image(image_filename, width=NoEscape(r"\linewidth")) left_kitten.add_caption("Kitten on the left") with doc.create(SubFigure(position="b", width=NoEscape(r"0.45\linewidth"))) as right_kitten: right_kitten.add_image(image_filename, width=NoEscape(r"\linewidth")) right_kitten.add_caption("Kitten on the right") kittens.add_caption("Two kittens") doc.generate_pdf()
# Test for list structures in PyLaTeX. # More info @ http://en.wikibooks.org/wiki/LaTeX/List_Structures from pylatex import Document, Section, Itemize, Enumerate, Description, \ Command, NoEscape if __name__ == '__main__': 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')):
# "color": "red", # "function": (lambda h, ncm, cm: ncm) # }, # { # "color": "red", # "function": (lambda h, ncm, cm: 0 if h + ncm == 0 else math.log10(h / (h + ncm + cm))) # } ] for identifier in identifiers: print("Preparing {}".format(identifier)) doc = Document() doc.packages.append(Package("geometry", options = ["tmargin=1cm", "lmargin=1cm"])) with doc.create(Section("Charts")): algorithms = ["fifo", "lru", "mru", "specialised"] # algorithms = ["mru", "specialised", "specialisedOrig"] data = { a: [] for a in algorithms } ymax = 0 for algorithm in algorithms: with open("../logs/{}_{}.log".format(identifier, algorithm)) as f: for line in f: m = re.match(r"^INFO: Cache stats: (\d+) h / (\d+) ncm / (\d+) cm .*? hr$", line) if m is not None: h, ncm, cm = m.groups() h, ncm, cm = int(h), int(ncm), int(cm) ymax = max(ymax, h, ncm, cm) data[algorithm].append((h, ncm, cm)) # data[algorithm] = data[algorithm][:400]