def read_and_fill_template(template_filepath: str, data: Optional[Dict] = None) -> Optional[str]: """ Builds the given template with the given data :param template_filepath: Path of the template to use :param data: Keywords-values for the given LaTeX-template :return: built LaTeX-report path if it was compiled, otherwise None """ # Make up the environment split_template_path = template_filepath.split('/') latex_templates_dir_path = '/'.join(split_template_path[:-1]) latex_template_path = split_template_path[-1] env = make_env(loader=FileSystemLoader(searchpath=latex_templates_dir_path), autoescape=False) # Get the template if not os.path.exists(template_filepath): logger.error(AGENT_UTILS_NAME, f'No template is found: {template_filepath}') return None template = env.get_template(latex_template_path) # Put the data into the template and render the text try: rendered_template = template.render(**data) except Exception as e: rendered_template = None logger.error(AGENT_UTILS_NAME, f'Can\'t render LaTeX template. Message: {e}') return rendered_template
def render(self): """ Render the boulder description and all problems into LaTex Parameters ---------- num : int Number of problem Returns ------- template : str Templated string """ #Create LaTex Jinja2 Environment env = make_env() tmpl = env.from_string(self.template) #Grab all stored boulder information info = copy.deepcopy(vars(self)) #Render all contained problems info.update({ 'problems': [prob.render(i + 1) for i, prob in enumerate(self.problems)] }) return tmpl.render(info)
def create_report(voters, title, fname): latex.build_pdf( make_env(loader=FileSystemLoader('.')).get_template( 'vrlist-template.tex').render( records=hierarchize_and_latexify_voters(voters), num_voters='{:,d}'.format(len(voters)), title=fix_latex_string(title), )).save_to(fname)
def generate( course_name, quiz_number, output_dir, template_file, recipients_file, token_file, s ): """Driver/interface function for generating a report. """ # Create directories if needed figures_dir = Path(output_dir / "figures") for d in [output_dir, figures_dir]: export.create_dir(d) # Use a stale dataset, or grab a fresh one if s is True: print("Loading contents from file...") with open("contents.json", "r") as f: contents = json.load(f) else: print("Fetching data from Canvas...") with token_file.open("r") as f: token = f.read() c = Canvas("asu.instructure.com", "v1", token) report_df = c.get_quiz_report(course_name, quiz_number) print("Fetch complete.") contents = data_processing.generate_report_contents( c, report_df, quiz_number, figures_dir, recipients_file ) with open("contents.json", "w+") as f: json.dump(contents, f) # Render LaTeX template print("Rendering LaTeX Template...") env = make_env(loader=FileSystemLoader(str(template_file.parent))) tpl = env.get_template(str(template_file.name)) rendered_latex = tpl.render(contents=contents) print("Render complete.") # Typeset PDF print("Typesetting PDF...") base_filename = f"muddy_points_{contents.get('quiz_number')}" pdf_filename = Path(output_dir / f"{base_filename}.pdf") pdf = build_pdf(rendered_latex, texinputs=[str(Path.cwd()), ""]) pdf.save_to(str(pdf_filename)) print("Typesetting complete.") # Export to Microsoft Word and LaTeX formats for further editing docx_filename = Path(output_dir / f"{base_filename}.docx") latex_filename = Path(output_dir / f"{base_filename}.tex") export.make_texfile(rendered_latex, latex_filename) export.make_docx(latex_filename, docx_filename) # Create archive print("Creating archive...") zip_filename = Path(output_dir / f"{base_filename}.zip") export.make_archive( zip_filename, [pdf_filename, docx_filename, latex_filename], figures_dir ) print(f"Created archive: {zip_filename}")
def render(self): """ Create main LaTex file for guidebook """ #Create LaTex Jinja2 Environment env = make_env(loader=PackageLoader('guidebook')) tmpl = env.get_template('main.tex') #Grab all area information info = {'areas' : [name_chapter(area.name) for area in self.areas]} return tmpl.render(info)
def generate_invoice(invoice): from jinja2.loaders import FileSystemLoader from latex.jinja2 import make_env from latex import build_pdf if (len(invoice.items) == 0): # skip invoices without items return latex_templates = '%s/templates/latex/' % dirname(ff_housing.__file__) env = make_env(loader=FileSystemLoader(latex_templates)) tpl = env.get_template('invoice.tex') pdf = build_pdf(tpl.render(invoice=invoice, templatedir=latex_templates)) pdf.save_to(invoice.path) return (invoice.path)
def render(self, main_tex='main.tex'): """ Create LaTex for area Parameters --------- main_tex : str, optional Relative location of main LaTex file. `main.tex` by default """ #Create LaTex Jinja2 Environment env = make_env(loader=PackageLoader('guidebook')) tmpl = env.get_template('area.tex') #Grab all area information info = copy.deepcopy(vars(self)) #Render all contained boulders and add main file location info.update({ 'boulders': [bldr.render() for bldr in self.boulders], 'main_tex': main_tex }) return tmpl.render(info)
def create_pdf(self, path): bg_image = self.bg_path.replace("\\", "/") logo = self.title_path.replace("\\", "/") models = sorted(self.models[self.root_name].items()) pprint(models) env = make_env(loader=FileSystemLoader(os.path.dirname(self.tex_path))) self.tpl = env.get_template(os.path.basename(self.tex_path)) print(self.tpl) render = self.tpl.render(logo=logo, bg_image=bg_image, models=models) print(render) self.pdf = build_pdf(render) self.pdf.save_to(path)
def build_cv(data, templates_dir, assets_dir): current_dir = os.path.abspath(os.path.dirname(__file__)) env = make_env(loader=FileSystemLoader('.')) tpl = env.get_template("{}cv.latex".format(templates_dir)) # Only pass str names for latex for publication in data["publications"]: publication["authors"] = [author["name"] for author in publication["authors"]] for project in data["student_projects"]: project["name"] = project["student"]["name"] tex = tpl.render(**data) # Write tex with open("{}vince-knight.tex".format(assets_dir), 'w') as f: f.write(tex) # Write pdf pdf = build_pdf(tex, texinputs=[current_dir, '']) pdf.save_to("{}vince-knight.pdf".format(assets_dir))
def build_cv(data, templates_dir, assets_dir): current_dir = os.path.abspath(os.path.dirname(__file__)) env = make_env(loader=FileSystemLoader('.')) tpl = env.get_template("{}cv.latex".format(templates_dir)) # Only pass str names for latex for publication in data["publications"]: publication["authors"] = [ author["name"] for author in publication["authors"] ] for project in data["student_projects"]: project["name"] = project["student"]["name"] tex = tpl.render(**data) # Write tex with open("{}vince-knight.tex".format(assets_dir), 'w') as f: f.write(tex) # Write pdf pdf = build_pdf(tex, texinputs=[current_dir, '']) pdf.save_to("{}vince-knight.pdf".format(assets_dir))
def render(self, num=0): """ Render the boulder problem in LaTex Parameters ---------- num : int Number of problem Returns ------- template : str Templated string """ #Create LaTex Jinja2 Environment env = make_env() tmpl = env.from_string(self.template) #Grab all stored route information info = copy.deepcopy(vars(self)) #Add problem number info['number'] = num #Add difficulty grouping info.update({'color': self.color}) return tmpl.render(info)
def generate_agreement(speakers): tpl = make_env( loader=FileSystemLoader('templates/')).get_template('agreement.tex') return build_pdf(tpl.render(speakers=speakers), texinputs=[os.getcwd() + '/templates/', ''])
def report(cfg): """ Create the pdf report. The latex formats for figures, tables, and summary paragraphs are created by templates in snowav/report/. Data is pulled from the snowav database. To add a figure to the report: - create the plot (of course) - add to variables dict in this file, with the same naming convention variables['PDEP_FIG'] = 'precip_depth%s.png'%(cfg.directory) - add figure template to snowav_report.tex \VAR{PDEP_FIG_TPL} - add to section_dict - add template to snowav/report/figs/ - add to snowav/config/CoreConfig.py [report] exclude_figs - if the figure may not exist (such as flt_diff, or those that require process() to run), address that with some form of exception before creating the pdf Args ------ cfg {class}: config class """ # bid = cfg.basins[cfg.plotorder[0]]['basin_id'] basins = cfg.basins wy_start = datetime(cfg.wy-1, 10, 1) start_date = cfg.start_date end_date = cfg.end_date run_name = cfg.run_name # edges = cfg.edges plotorder = cfg.plotorder dpts = int(cfg.dplcs) ddpts = int(cfg.rep_dplcs) cnx = cfg.connector # variables to pass to latex file variables = {} dbval = collect(cnx, plotorder[0], basins, wy_start, end_date, 'swi_vol', run_name, 'total', 'sum') variables['TOTAL_SWI'] = dbval.sum().values.round(decimals=dpts)[0] dbval = collect(cnx, plotorder[0], basins, start_date, end_date, 'swi_vol', run_name, 'total', 'sum') variables['PER_SWI'] = dbval.sum().values.round(decimals=dpts)[0] dbval = collect(cnx, plotorder[0], basins, start_date, end_date, 'swe_vol', run_name, 'total', 'end') variables['TOTAL_SWE'] = dbval.sum().values.round(decimals=dpts)[0] dbval = collect(cnx, plotorder[0], basins, start_date, end_date, 'swe_avail', run_name, 'total', 'end') variables['TOTAL_SAV'] = dbval.sum().values.round(decimals=dpts)[0] dbval = collect(cnx, plotorder[0], basins, start_date, end_date, 'swe_z', run_name, 'total', 'end') variables['TOTAL_PM'] = dbval.sum().values.round(decimals=ddpts)[0] dbval = collect(cnx, plotorder[0], basins, wy_start, end_date, 'precip_z', run_name, 'total', 'sum') variables['TOTALPRE_PM'] = dbval.sum().values.round(decimals=ddpts)[0] s = collect(cnx, plotorder[0], basins, start_date, start_date, 'swe_vol', run_name, 'total', 'end') e = collect(cnx, plotorder[0], basins, start_date, end_date, 'swe_vol', run_name, 'total', 'end') start_swe = s.sum().values.round(decimals=dpts)[0] end_swe = e.sum().values.round(decimals=dpts)[0] diff = end_swe - start_swe variables['TOTAL_SDEL'] = diff variables['TOTAL_PVOL'] = '100' if float(end_swe) - float(start_swe) > 0: variables['SIGN'] = r'$+$' if float(end_swe) - float(start_swe) == 0.0: variables['SIGN'] = '' if float(end_swe) - float(start_swe) < 0.0: variables['SIGN'] = r'-' dbval = collect(cnx, plotorder[0], basins, wy_start, end_date, 'rain_z', run_name, 'total', 'sum') total_rain = dbval.sum().values.round(decimals=ddpts)[0] if variables['TOTALPRE_PM'] != 0: variables['TOTAL_RAT'] = str(int((total_rain / variables['TOTALPRE_PM']) * 100)) else: variables['TOTAL_RAT'] = '-' variables['TOTALPRE_PM'] = '-' report_time = datetime.now().strftime("%Y-%-m-%-d %H:%M") numsubs = range(1, len(cfg.plotorder)) for n, sub in zip(numsubs, cfg.plotorder[1:]): swiind = 'SUB' + str(n) + '_SWI' perswiind = 'SUB' + str(n) + '_PERSWI' sweind = 'SUB' + str(n) + '_SWE' avsweind = 'SUB' + str(n) + '_SAV' swedel = 'SUB' + str(n) + '_SDEL' pm = 'SUB' + str(n) + '_PM' prepm = 'SUB' + str(n) + 'PRE_PM' rain = 'SUB' + str(n) + 'RAI' ratio = 'SUB' + str(n) + '_RAT' pvol = 'SUB' + str(n) + '_PVOL' dbval = collect(cnx, sub, basins, wy_start, end_date, 'swi_vol', run_name, 'total', 'sum') variables[swiind] = dbval.sum().values.round(decimals=dpts)[0] dbval = collect(cnx, sub, basins, start_date, end_date, 'swi_vol', run_name, 'total', 'sum') variables[perswiind] = dbval.sum().values.round(decimals=dpts)[0] dbval = collect(cnx, sub, basins, start_date, end_date, 'swe_vol', run_name, 'total', 'end') variables[sweind] = dbval.sum().values.round(decimals=dpts)[0] dbval = collect(cnx, sub, basins, start_date, end_date, 'swe_avail', run_name, 'total', 'end') variables[avsweind] = dbval.sum().values.round(decimals=dpts)[0] dbval = collect(cnx, sub, basins, start_date, start_date, 'swe_vol', run_name, 'total', 'end') start_swe = dbval.sum().values.round(decimals=dpts)[0] dbval = collect(cnx, sub, basins, start_date, end_date, 'swe_vol', run_name, 'total', 'end') end_swe = dbval.sum().values.round(decimals=dpts)[0] variables[swedel] = end_swe - start_swe dbval = collect(cnx, sub, basins, start_date, end_date, 'swe_z', run_name, 'total', 'end') variables[pm] = dbval.sum().values.round(decimals=ddpts)[0] dbval = collect(cnx, sub, basins, wy_start, end_date, 'precip_z', run_name, 'total', 'sum') variables[prepm] = dbval.sum().values.round(decimals=ddpts)[0] dbval = collect(cnx, sub, basins, wy_start, end_date, 'rain_z', run_name, 'total', 'sum') variables[rain] = dbval.sum().values.round(decimals=ddpts)[0] if (end_swe > 0) and (variables['TOTAL_SWE'] > 0): variables[pvol] = end_swe / variables['TOTAL_SWE'] * 100 else: variables[pvol] = '-' if variables[prepm] != 0.0: variables[ratio] = str(int((variables[rain] / variables[prepm]) * 100)) else: variables[ratio] = '0' # Upper case variables are used in the LaTex file, # lower case versions are assigned here # untested - if report title contains comma? if isinstance(cfg.rep_title, list): title = cfg.rep_title[0] for s in cfg.rep_title[1::]: title = title + ', ' + s variables['REPORT_TITLE'] = title else: if cfg.flt_flag and cfg.flight_figs: fst = ' Model snow depths were updated with ASO snow depths on ' tst = '' for i, d in enumerate(cfg.flight_diff_dates): if d <= cfg.end_date: dn = d.date().strftime("%m/%d") if len(cfg.flight_diff_dates) == 1: fst = fst + dn + '.' tst += dn if ((len(cfg.flight_diff_dates) > 1) and (i < len(cfg.flight_diff_dates) - 1)): fst = fst + dn + ', ' tst += dn + ', ' if ((len(cfg.flight_diff_dates) > 1) and (i == len(cfg.flight_diff_dates) - 1)): fst = fst + 'and ' + dn + '.' tst += dn else: fst = fst.split(dn)[0] + 'and ' + dn + '.' break variables['REPORT_TITLE'] = (cfg.rep_title + r' \\ ASO Updates {}'.format(tst)) variables['FLTSENT'] = fst else: variables['REPORT_TITLE'] = cfg.rep_title variables['FLTSENT'] = '' variables['REPORT_TIME'] = report_time variables['WATERYEAR'] = str(cfg.wy) variables['UNITS'] = cfg.vollbl variables['VOLLBL'] = cfg.vollbl variables['DEPLBL'] = cfg.depthlbl variables['START_DATE'] = cfg.report_start.date().strftime("%B %-d") variables['END_DATE'] = cfg.report_date.date().strftime("%B %-d") variables['SWE_IN'] = variables['TOTAL_PM'] variables['SWI_IN'] = variables['TOTAL_SWI'] variables['FIG_PATH'] = cfg.figs_path variables['SWI_FIG'] = cfg.swi_volume_fig_name variables['CHANGES_FIG'] = cfg.volume_change_fig_name variables['TOTALS_FIG'] = cfg.basin_total_fig_name variables['MULTITOTSWE_FIG'] = 'compare_swe_vol_{}.png'.format(cfg.directory) variables['PDEP_FIG'] = cfg.precip_fig_name variables['VALID_FIG'] = cfg.stn_validate_fig_name variables['COLD_FIG'] = cfg.cold_content_fig_name variables['SWE_FIG'] = cfg.swe_volume_fig_name variables['VERSION'] = snowav.__version__ if (cfg.update_file is not None) and cfg.flt_flag and cfg.flight_figs: for name in cfg.flight_diff_fig_names: variables['DFLT_FIG'] = name if cfg.report_diagnostics: variables['DIAGNOSTICS_FIG'] = 'diagnostics_{}'.format(cfg.directory) variables['INPUTS_FIG'] = 'inputs_period_{}'.format(cfg.directory) if cfg.subs_fig is not None: variables['SUBBASINS_FIG'] = '{}'.format(cfg.subs_fig) # Logos variables['ARSLOGO'] = os.path.join(cfg.figs_tpl_path, 'ARS.jpg') variables['ASOLOGO'] = os.path.join(cfg.figs_tpl_path, 'ASO.jpg') variables['USDALOGO'] = os.path.join(cfg.figs_tpl_path, 'USDA.png') variables['JPLLOGO'] = os.path.join(cfg.figs_tpl_path, 'JPL.jpg') variables['CDWRLOGO'] = os.path.join(cfg.figs_tpl_path, 'CDWR.png') variables['USBRLOGO'] = os.path.join(cfg.figs_tpl_path, 'USBR.jpg') variables['NRCSLOGO'] = os.path.join(cfg.figs_tpl_path, 'NRCS.jpg') variables['KRWALOGO'] = os.path.join(cfg.figs_tpl_path, 'KRWA.jpg') variables['FRIANTLOGO'] = os.path.join(cfg.figs_tpl_path, 'FRIANT.jpg') variables['AWSMLOGO'] = os.path.join(cfg.figs_tpl_path, 'logo.png') dfind = [str(i) for i in cfg.edges] dfindt = [str(i) for i in cfg.edges] + ['total'] colstr = 'l' + 'r' * len(cfg.plotorder) if len(cfg.plotorder) > 5: spacecmd = r'\resizebox{\textwidth}{!}{' else: spacecmd = r'{' # ntables = len(cfg.tables) mtables = 2 ptables = 0 if 'swe_depth' in cfg.tables: dbval = collect(cnx, plotorder, basins, start_date, end_date, 'swe_z', run_name, dfindt, 'end') dbval = dbval.rename(columns=cfg.labels) swe_byelev = dbval.round(decimals=dpts) swe_byelev.rename(index={'total': 'mean'}, inplace=True) swe_byelev.index.name = 'Elevation' variables['SWE_BYELEV'] = (r' \normalsize \textbf{SWE [%s], %s}\\ \vspace{0.1cm} \\' % (cfg.depthlbl, cfg.report_date.date().strftime("%Y-%-m-%-d")) + spacecmd + swe_byelev.to_latex(na_rep='-', column_format=colstr) + r'} \\ \footnotesize{\textbf{Table %s:} SWE depth.}' % (str(mtables))) mtables += 1 ptables += 1 else: variables['SWE_BYELEV'] = '' if 'swe_vol' in cfg.tables: ptables += 1 if ptables == 2: clrpage = r'\clearpage' else: clrpage = '' dbval = collect(cnx, plotorder, basins, start_date, end_date, 'swe_vol', run_name, dfindt, 'end') dbval = dbval.rename(columns=cfg.labels) swe_byelev = dbval.round(decimals=dpts) swe_byelev.index.name = 'Elevation' variables['SWEVOL_BYELEV'] = (r' \normalsize \textbf{SWE [%s], %s}\\ \vspace{0.1cm} \\' % (cfg.vollbl, cfg.report_date.date().strftime("%Y-%-m-%-d")) + spacecmd + swe_byelev.to_latex(na_rep='-', column_format=colstr) + r'} \\ \footnotesize{\textbf{Table %s:} SWE volume.}%s' % (str(mtables), clrpage)) mtables += 1 else: variables['SWEVOL_BYELEV'] = '' if 'swe_change' in cfg.tables: ptables += 1 if ptables == 2: clrpage = r'\clearpage' else: clrpage = '' dbval = collect(cnx, plotorder, basins, start_date, start_date, 'swe_z', run_name, dfindt, 'end') dbval = dbval.rename(columns=cfg.labels) start_swe = dbval.round(decimals=dpts) dbval = collect(cnx, plotorder, basins, start_date, end_date, 'swe_z', run_name, dfindt, 'end') dbval = dbval.rename(columns=cfg.labels) end_swe = dbval.round(decimals=dpts) dswe_byelev = end_swe - start_swe dswe_byelev.rename(index={'total': 'mean'}, inplace=True) dswe_byelev.index.name = 'Elevation' variables['DSWE_BYELEV'] = (r' \normalsize \textbf{Change in SWE [%s], %s to %s}\\ \vspace{0.1cm} \\' % (cfg.depthlbl, cfg.report_start.date().strftime("%Y-%-m-%-d"), cfg.report_date.date().strftime("%Y-%-m-%-d")) + spacecmd + dswe_byelev.to_latex(na_rep='-', column_format=colstr) + r'} \\ \footnotesize{\textbf{Table %s:} Change in SWE.} %s' % ( str(mtables), clrpage)) mtables += 1 else: variables['DSWE_BYELEV'] = '' if 'swe_percent' in cfg.tables: ptables += 1 if (ptables % 2) == 0 and ptables != 0: clrpage = r'\clearpage' else: clrpage = '' dbval = collect(cnx, plotorder, basins, start_date, end_date, 'swe_vol', run_name, dfind, 'end') dbval = dbval.rename(columns=cfg.labels) swe_byelev = dbval.round(decimals=dpts) value = swe_byelev.iloc[:-1].sum() sweper_byelev = (swe_byelev / value * 100).round(decimals=dpts) sweper_byelev.index.name = 'Elevation' variables['SWEPER_BYELEV'] = ( r' \normalsize \textbf{SWE volume, percent of basin total, %s}\\ \vspace{0.1cm} \\' % (cfg.report_date.date().strftime("%Y-%-m-%-d")) + spacecmd + sweper_byelev.round(1).to_latex(na_rep='-', column_format=colstr) + r'} \\ \footnotesize{\textbf{Table %s:} Percent of total SWE volume.}%s' % (str(mtables), clrpage)) variables['SWEPER_BYELEV'] = variables['SWEPER_BYELEV'].replace('inf', '-') mtables += 1 else: variables['SWEPER_BYELEV'] = '' if 'swi_vol' in cfg.tables: dbval = collect(cnx, plotorder, basins, start_date, end_date, 'swi_vol', run_name, dfindt, 'sum') dbval = dbval.rename(columns=cfg.labels) swi_byelev = dbval.round(decimals=dpts) variables['ACCUM_BYELEV'] = (r' \normalsize \textbf{SWI [%s] by elevation, %s to %s}\\ \vspace{0.1cm} \\' % (cfg.vollbl, cfg.report_start.date().strftime("%Y-%-m-%-d"), cfg.report_date.date().strftime("%Y-%-m-%-d")) + spacecmd + swi_byelev.to_latex(na_rep='-', column_format=colstr) + r'} \\ \footnotesize{\textbf{Table %s:} SWI volume. }' % (str(mtables))) mtables += 1 else: variables['ACCUM_BYELEV'] = '' variables['TOT_LBL'] = cfg.plotorder[0] # for n in range(1,len(cfg.plotorder)): for n in range(1, len(cfg.labels)): s = 'SUB' + str(n) + '_LBL' variables[s] = cfg.labels[cfg.plotorder[n]] # Convert floats to strings for name in variables: if isinstance(variables[name], float): if cfg.dplcs == 0: tmp = str(int(variables[name])) else: tmp = str(round(variables[name], cfg.dplcs)) variables[name] = tmp # Summary sections and fig template have variable strings # (e.g. CHANGES_FIG) that need to be replaced section_dict = {'SUMMARY': cfg.summary_file, 'CHANGES_FIG_TPL': os.path.join(cfg.figs_tpl_path, 'changes_fig_tpl.txt'), 'SWI_FIG_TPL': os.path.join(cfg.figs_tpl_path, 'swi_fig_tpl.txt'), 'TOTALS_FIG_TPL': os.path.join(cfg.figs_tpl_path, 'totals_fig_tpl.txt'), 'MULTITOTSWE_FIG_TPL': os.path.join(cfg.figs_tpl_path, 'multitotswe_fig_tpl.txt'), 'VALID_FIG_TPL': os.path.join(cfg.figs_tpl_path, 'valid_fig_tpl.txt'), 'FLTCHANGES_FIG_TPL': os.path.join(cfg.figs_tpl_path, 'flt_fig_tpl.txt'), 'PDEP_FIG_TPL': os.path.join(cfg.figs_tpl_path, 'pdep_fig_tpl.txt'), 'COLD_FIG_TPL': os.path.join(cfg.figs_tpl_path, 'cold_fig_tpl.txt'), 'SWE_FIG_TPL': os.path.join(cfg.figs_tpl_path, 'swe_fig_tpl.txt'), 'SUBBASINS_FIG_TPL': os.path.join(cfg.figs_tpl_path, 'subbasins_fig_tpl.txt'), 'DIAGNOSTICS_FIG_TPL': os.path.join(cfg.figs_tpl_path, 'diagnostics_fig_tpl.txt'), 'SWE_SUMMARY_TPL': os.path.join(cfg.figs_tpl_path, 'swe_summary_{}sub.txt'.format(str(len(cfg.plotorder))))} # Define and load summary tables depending on number of subbasins # Remove if no flight if not cfg.flt_flag or not cfg.flight_figs: del section_dict['FLTCHANGES_FIG_TPL'] if not cfg.report_diagnostics: del section_dict['DIAGNOSTICS_FIG_TPL'] variables['DIAGNOSTICS_FIG'] = '' for rep in section_dict.keys(): # for variable numbers of fligth figures if rep == 'FLTCHANGES_FIG_TPL': fid = open(section_dict[rep], 'r') var = fid.read() fid.close() for name in sorted(variables): if name == 'DFLT_FIG': for i, fltname in enumerate(cfg.flight_diff_fig_names): flt_date = cfg.flight_outputs['dates'][i].date().strftime("%Y%m%d") flt_num = cfg.flight_delta_vol_df[flt_date].round(1).to_latex(na_rep='-', column_format=colstr) table = (r'{ \vspace{0.5cm} \textbf{Change in SWE [%s] by elevation, ' % (cfg.vollbl) + r'from %s update} \\ \vspace{0.1cm} \\' % (flt_date) + r' %s %s }' % (spacecmd, flt_num)) if i == 0: tmp = var.replace(name, fltname) else: tmp += var.replace(name, fltname) tmp += table var = tmp.replace(name, variables[name]) else: var = var.replace(name, variables[name]) variables[rep] = var else: fid = open(section_dict[rep], 'r') var = fid.read() fid.close() for name in sorted(variables): var = var.replace(name, variables[name]) variables[rep] = var if not cfg.subs_fig: variables['SUBBASINS_FIG_TPL'] = '' if not cfg.rep_compare_runs_flag: variables['MULTITOTSWE_FIG_TPL'] = '' if not cfg.rep_swi_flag: variables['SWI_FIG_TPL'] = '' if not cfg.rep_image_change_flag: variables['CHANGES_FIG_TPL'] = '' if not cfg.rep_cold_content_flag: variables['COLD_FIG_TPL'] = '' if not cfg.rep_swe_volume_flag: variables['SWE_FIG_TPL'] = '' if not cfg.rep_basin_total_flag: variables['TOTALS_FIG_TPL'] = '' if not cfg.rep_stn_validate_flag: variables['VALID_FIG_TPL'] = '' if not cfg.rep_compare_runs_flag: variables['MULTITOTSWE_FIG_TPL'] = '' if not cfg.rep_precip_depth_flag: variables['PDEP_FIG_TPL'] = '' # Make the report env = make_env(loader=FileSystemLoader(cfg.templ_path)) tpl = env.get_template(cfg.tex_file) # print VAR-replaced latex file for debugging if desired if cfg.print_latex: print(tpl.render(variables)) pdf = build_pdf(tpl.render(variables)) # Save in reports and with figs rpath = os.path.join(cfg.figs_path, '' + cfg.report_name) pdf.save_to(rpath) cfg._logger.info(' Saved {}'.format(rpath)) if cfg.rep_path is not None: rpath = os.path.join(cfg.rep_path, '' + cfg.report_name) pdf.save_to(rpath) cfg._logger.info(' Saved {}'.format(rpath))
import os import re import yaml import click import frontmatter from jinja2.loaders import FileSystemLoader from latex import build_pdf from latex.jinja2 import make_env env = make_env(loader=FileSystemLoader('template/')) base = env.get_template('base.tex') recipe = env.get_template('recipe.tex') itemization = env.get_template('itemize.tex') enumeration = env.get_template('enumerate.tex') multicol = env.get_template('multicol.tex') def process_directions(array, item, template=itemization): subsections = [] for subsection in array: title = subsection['title'] items = subsection[item] text = r'\textit{' + title + '}\n' \ + template.render(items=items) subsections.append(text)
""" Example cribbed mostly from https://pythonhosted.org/latex/ """ from flask import Flask from jinja2 import FileSystemLoader from latex import build_pdf from latex.jinja2 import make_env app = Flask(__name__) env = make_env(loader=FileSystemLoader('.')) @app.route('/') def home(): template = env.get_template('ex2.latex') pdf = build_pdf(template.render(name='Alice')) return bytes(pdf), 200, { 'Content-Type': 'application/pdf', 'Content-Disposition': 'inline; filename="report.pdf"' }
import sys from jinja2 import FileSystemLoader from latex.jinja2 import make_env from latex import build_pdf if len(sys.argv) != 2: print "Provide the path to the file containing the text of the body of the faxes." print "e.g.> %s file.txt" % (sys.argv[0]) sys.exit(1) FAXPATH = sys.argv[1] with open(FAXPATH, 'r') as myfile: FAXTEXT = myfile.read().replace('\n', ' ') CURRENT_DIR = os.path.abspath(os.path.dirname(__file__)) ENV = make_env(loader=FileSystemLoader(".")) TEMPLATE = ENV.get_template('fax.latex') with open("sender.csv") as sendercsv: SENDER = csv.DictReader(sendercsv).next() ADDRESSEES = [] with open("addressees.csv") as addressees: for entry in csv.DictReader(addressees): # Addresses are '|' delimited. Convert to latex newlines '\\' entry['addressee'] = "\\\\".join(entry['address'].split("|")) +\ "\\\\FAX: %s" % entry['fax_number'] # Create a filename for this addressee entry['filename'] = entry['greeting'].lower().replace(' ', '_') + ".pdf" entry['signature'] = SENDER['signature_file']
# Read roles with open("../_data/roles.yml", "r") as f: roles = yaml.load(f) # Read research interests with open("../_data/research_topics.yml", "r") as f: interests = yaml.load(f) # Read awards with open("../_data/awards.yml", "r") as f: awards = yaml.load(f) current_dir = os.path.abspath(os.path.dirname(__file__)) env = make_env(loader=FileSystemLoader('.')) tpl = env.get_template('cv.latex') tex = tpl.render(appointments=appointments, qualifications=qualifications, publications=publications, students=students, courses=courses, grants=grants, media=media, outreach_activities=outreach_activities, software_projects=software_projects, software_communities=software_communities, roles=roles, interests=interests, awards=awards,
def algorithmLaTeX(self, caption=None, coefFormat=None, withTime=False, withSurname=False, label=None): """ Generate a tex file to use with package algorithm2e to create a LaTex output of algorithm - `caption` is an additional caption """ def declare(lvar, Kwname, isStatic=False, suffix=''): """generate algorithm2e code to declare variables""" if len(lvar) == 0: return '' elif len(lvar) == 1: return '\\%s{$%s$: %sreal}' % (Kwname, lvar[0].name + suffix, 'static ' if isStatic else '') else: return '\\%s{$%s$: %sarray [1..%d] of reals}' % ( Kwname, lvar[0].name + suffix, 'static ' if isStatic else '', len(lvar)) env = make_env(loader=FileSystemLoader(SIF_TEMPLATES_PATH)) tpl = env.get_template('algorithmLaTeX_template.tex') algoStr = [ s + r"\\" for s in self._algorithmCore(LaTeX=True, assign='$\leftarrow$', coefFormat=coefFormat, withTime=withTime, withSurname=withSurname) ] # add comments algoStr.insert(self._l + self._n, r"\tcp{Outputs}" if self._p > 1 else r"\tcp{Output}") if self._n > 0: algoStr.insert(self._l, r"\tcp{States}" if self._n > 1 else r"\tcp{State}") if self._l > 0: algoStr.insert( 0, r"\tcp{Temporary variables}" if self._l > 1 else r"\tcp{Temporary variable}") if withTime is False and self.isPnut(): algoStr.append(r"\tcp{Swap states}") algoStr.append("$" + self._varNameX[0].name + ' \leftarrow ' + self._varNameX[0].name + "p$") # caption if caption is None: caption = utf8tolatex( self.name ) # TODO: complete ? caption should be a string, where we can insert self._Filter.name (like 'My algorithm of %s', or 'my algo' if we do not want to use self._Filter.name) # label label = '' if label is None else '\label{' + label + '}' # initialization init = [ declare(self._varNameU, 'KwIn'), declare(self._varNameY, 'KwOut'), declare(self._varNameX, 'KwData', isStatic=True), declare(self._varNameT, 'KwData') ] if withTime is False and self.isPnut(): init.append(declare(self._varNameX, 'KwData', suffix='p')) return tpl.render(computations="\n".join(algoStr), caption=caption, initialization="\n".join(init), date=str(datetime.now()), SIF=self.name, label=label)
key: item[key] for key in [ 'recipeid', 'recipetitle', 'firstline', 'recipemeta', 'recipetext', 'recipenotes' ] } if recipeid == None: return jsonify(recipes=list(map(filter_keys, recipe_list))) if recipeid in recipe_dict: return jsonify(filter_keys(recipe_dict[recipeid])) else: return abort(404) texenv = make_env(loader=app.jinja_loader) @app.route('/recipes.pdf') def pdf(): texonly = 'texonly' in request.args orientation = 'landscape' if 'landscape' in request.args else 'portrait' cols = request.args.get('cols') or 2 font = request.args.get('font') fontoptions = request.args.get('fontoptions') recipeids = request.args.get('recipeids') if recipeids: try: recipeids = map(int, recipeids.split(',')) except ValueError:
def generate_quittance(input_dict): check_input(input_dict) first_date = datetime.strptime(input_dict['first_date'], '%m %Y') last_date = datetime.strptime(input_dict['last_date'], '%m %Y') rent = float(input_dict['rent']) charges = float(input_dict['charges']) total_amount = rent + charges input_dict['total_amount'] = locale.currency(total_amount, symbol=False) input_dict['rent'] = locale.currency(rent, symbol=False) input_dict['charges'] = locale.currency(charges, symbol=False) tenants = input_dict['tenants'].split(",") # Elision du locataire dtenants = [de_elision(tenants[0])] + tenants[1:] if len(tenants) > 1: dtenants = " et ".join(dtenants) tenants = " et ".join(tenants) pronoun = "leur" else: dtenants = dtenants[0] tenants = tenants[0] pronoun = "lui" # Get sign_date or return today sign_date = input_dict.get('sign_date', "{0:%d} {0:%B} {0:%Y}".format(datetime.now())) for d in rrule(MONTHLY, dtstart=datetime(first_date.year, first_date.month, 1), until=datetime(last_date.year, last_date.month, 1)): file_name = "{0:%Y}_{0:%m}_quittance.pdf".format(d) directory = "quittances" if not os.path.exists(directory): os.makedirs(directory) file_path = os.path.join(directory, file_name) mois_de = de_elision("{:%B}".format(d)) # Elision du mois start_date = "1er {0:%B} {0:%Y}".format(d) end_date = "{1} {0:%B} {0:%Y}".format(d, monthrange(d.year, d.month)[1]) doc_date = "{}-{}".format(d.year, d.month) m_dict = {} m_dict.update(input_dict) m_dict.update({ 'tenant': tenants, 'dtenant': dtenants, 'pronoun': pronoun, 'month': mois_de, 'year': "{:%Y}".format(d), 'start': start_date, 'end': end_date, 'pay_date': start_date, 'sign_date': sign_date, 'doc_date': doc_date }) env = make_env(loader=FileSystemLoader('.')) tpl = env.get_template('template.tex') latex_file = tpl.render(**m_dict) pdf = build_pdf(latex_file) pdf.save_to(file_path) print(file_path)
from flask import Flask, request, Response, redirect, render_template from latex import build_pdf, LatexBuildError from latex.jinja2 import make_env app = Flask(__name__, static_url_path='/static') texenv = make_env(loader=app.jinja_loader) @app.route('/') @app.route('/motion') @app.route('/proposition') @app.route('/reply') def index(): return render_template('index.html') @app.route('/motion.pdf', methods=['POST']) def pdf(): try: if not 'items[]' in request.form: return redirect('/') if not 'authors[]' in request.form: return redirect('/') pdffile = build_pdf(get_tex()) return Response(pdffile.stream, mimetype='application/pdf') except LatexBuildError as e: return Response(tex, mimetype='application/x-tex') @app.route('/motion.tex', methods=['POST']) def tex(): return Response(get_tex(), mimetype='application/x-tex')
data = read_file(args.filename) # split source directory and filename source_dir, filename = os.path.split(args.filename) filename = os.path.splitext(filename)[0] working_dir = os.getcwd() new_invoice = Invoice(data) if new_invoice.language == 'en': locale.setlocale(locale.LC_ALL, 'en_US.utf8') new_invoice.prepare_data() new_invoice.create_invoiceitemlist() context = collect_context(new_invoice) env = make_env(loader=FileSystemLoader(working_dir + '/templates/')) template = select_template() create_pdf(filename, template, context) if (args.timesheet == 'timesheet'): itemslist = new_invoice.invoiceitemlist for item in itemslist: item.sum = locale.currency(item.sum, symbol=False) context['itemslist'] = itemslist if new_invoice.language == 'eng': template = env.get_template('stundennachweis-eng.tex') else: template = env.get_template('stundennachweis.tex') create_pdf(filename + '_timesheet', template, context)